CodeGenFunction.h 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  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 is the internal per-function state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  15. #include "CGBuilder.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGLoopInfo.h"
  18. #include "CGValue.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "EHScopeStack.h"
  22. #include "VarBypassDetector.h"
  23. #include "clang/AST/CharUnits.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/ExprOpenMP.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/Basic/ABI.h"
  29. #include "clang/Basic/CapturedStmt.h"
  30. #include "clang/Basic/OpenMPKinds.h"
  31. #include "clang/Basic/TargetInfo.h"
  32. #include "clang/Frontend/CodeGenOptions.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/ADT/DenseMap.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include "llvm/IR/ValueHandle.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Transforms/Utils/SanitizerStats.h"
  39. namespace llvm {
  40. class BasicBlock;
  41. class LLVMContext;
  42. class MDNode;
  43. class Module;
  44. class SwitchInst;
  45. class Twine;
  46. class Value;
  47. class CallSite;
  48. }
  49. namespace clang {
  50. class ASTContext;
  51. class BlockDecl;
  52. class CXXDestructorDecl;
  53. class CXXForRangeStmt;
  54. class CXXTryStmt;
  55. class Decl;
  56. class LabelDecl;
  57. class EnumConstantDecl;
  58. class FunctionDecl;
  59. class FunctionProtoType;
  60. class LabelStmt;
  61. class ObjCContainerDecl;
  62. class ObjCInterfaceDecl;
  63. class ObjCIvarDecl;
  64. class ObjCMethodDecl;
  65. class ObjCImplementationDecl;
  66. class ObjCPropertyImplDecl;
  67. class TargetInfo;
  68. class VarDecl;
  69. class ObjCForCollectionStmt;
  70. class ObjCAtTryStmt;
  71. class ObjCAtThrowStmt;
  72. class ObjCAtSynchronizedStmt;
  73. class ObjCAutoreleasePoolStmt;
  74. namespace analyze_os_log {
  75. class OSLogBufferLayout;
  76. }
  77. namespace CodeGen {
  78. class CodeGenTypes;
  79. class CGCallee;
  80. class CGFunctionInfo;
  81. class CGRecordLayout;
  82. class CGBlockInfo;
  83. class CGCXXABI;
  84. class BlockByrefHelpers;
  85. class BlockByrefInfo;
  86. class BlockFlags;
  87. class BlockFieldFlags;
  88. class RegionCodeGenTy;
  89. class TargetCodeGenInfo;
  90. struct OMPTaskDataTy;
  91. struct CGCoroData;
  92. /// The kind of evaluation to perform on values of a particular
  93. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  94. /// CGExprAgg?
  95. ///
  96. /// TODO: should vectors maybe be split out into their own thing?
  97. enum TypeEvaluationKind {
  98. TEK_Scalar,
  99. TEK_Complex,
  100. TEK_Aggregate
  101. };
  102. #define LIST_SANITIZER_CHECKS \
  103. SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
  104. SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
  105. SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
  106. SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
  107. SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
  108. SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
  109. SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
  110. SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
  111. SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
  112. SANITIZER_CHECK(MissingReturn, missing_return, 0) \
  113. SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
  114. SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
  115. SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
  116. SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
  117. SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
  118. SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
  119. SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
  120. SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
  121. SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
  122. SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
  123. SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
  124. SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
  125. enum SanitizerHandler {
  126. #define SANITIZER_CHECK(Enum, Name, Version) Enum,
  127. LIST_SANITIZER_CHECKS
  128. #undef SANITIZER_CHECK
  129. };
  130. /// CodeGenFunction - This class organizes the per-function state that is used
  131. /// while generating LLVM code.
  132. class CodeGenFunction : public CodeGenTypeCache {
  133. CodeGenFunction(const CodeGenFunction &) = delete;
  134. void operator=(const CodeGenFunction &) = delete;
  135. friend class CGCXXABI;
  136. public:
  137. /// A jump destination is an abstract label, branching to which may
  138. /// require a jump out through normal cleanups.
  139. struct JumpDest {
  140. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  141. JumpDest(llvm::BasicBlock *Block,
  142. EHScopeStack::stable_iterator Depth,
  143. unsigned Index)
  144. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  145. bool isValid() const { return Block != nullptr; }
  146. llvm::BasicBlock *getBlock() const { return Block; }
  147. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  148. unsigned getDestIndex() const { return Index; }
  149. // This should be used cautiously.
  150. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  151. ScopeDepth = depth;
  152. }
  153. private:
  154. llvm::BasicBlock *Block;
  155. EHScopeStack::stable_iterator ScopeDepth;
  156. unsigned Index;
  157. };
  158. CodeGenModule &CGM; // Per-module state.
  159. const TargetInfo &Target;
  160. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  161. LoopInfoStack LoopStack;
  162. CGBuilderTy Builder;
  163. // Stores variables for which we can't generate correct lifetime markers
  164. // because of jumps.
  165. VarBypassDetector Bypasses;
  166. // CodeGen lambda for loops and support for ordered clause
  167. typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
  168. JumpDest)>
  169. CodeGenLoopTy;
  170. typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
  171. const unsigned, const bool)>
  172. CodeGenOrderedTy;
  173. // Codegen lambda for loop bounds in worksharing loop constructs
  174. typedef llvm::function_ref<std::pair<LValue, LValue>(
  175. CodeGenFunction &, const OMPExecutableDirective &S)>
  176. CodeGenLoopBoundsTy;
  177. // Codegen lambda for loop bounds in dispatch-based loop implementation
  178. typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
  179. CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
  180. Address UB)>
  181. CodeGenDispatchBoundsTy;
  182. /// \brief CGBuilder insert helper. This function is called after an
  183. /// instruction is created using Builder.
  184. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  185. llvm::BasicBlock *BB,
  186. llvm::BasicBlock::iterator InsertPt) const;
  187. /// CurFuncDecl - Holds the Decl for the current outermost
  188. /// non-closure context.
  189. const Decl *CurFuncDecl;
  190. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  191. const Decl *CurCodeDecl;
  192. const CGFunctionInfo *CurFnInfo;
  193. QualType FnRetTy;
  194. llvm::Function *CurFn;
  195. // Holds coroutine data if the current function is a coroutine. We use a
  196. // wrapper to manage its lifetime, so that we don't have to define CGCoroData
  197. // in this header.
  198. struct CGCoroInfo {
  199. std::unique_ptr<CGCoroData> Data;
  200. CGCoroInfo();
  201. ~CGCoroInfo();
  202. };
  203. CGCoroInfo CurCoro;
  204. bool isCoroutine() const {
  205. return CurCoro.Data != nullptr;
  206. }
  207. /// CurGD - The GlobalDecl for the current function being compiled.
  208. GlobalDecl CurGD;
  209. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  210. /// cleanups associated with the parameters.
  211. EHScopeStack::stable_iterator PrologueCleanupDepth;
  212. /// ReturnBlock - Unified return block.
  213. JumpDest ReturnBlock;
  214. /// ReturnValue - The temporary alloca to hold the return
  215. /// value. This is invalid iff the function has no return value.
  216. Address ReturnValue;
  217. /// Return true if a label was seen in the current scope.
  218. bool hasLabelBeenSeenInCurrentScope() const {
  219. if (CurLexicalScope)
  220. return CurLexicalScope->hasLabels();
  221. return !LabelMap.empty();
  222. }
  223. /// AllocaInsertPoint - This is an instruction in the entry block before which
  224. /// we prefer to insert allocas.
  225. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  226. /// \brief API for captured statement code generation.
  227. class CGCapturedStmtInfo {
  228. public:
  229. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  230. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  231. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  232. CapturedRegionKind K = CR_Default)
  233. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  234. RecordDecl::field_iterator Field =
  235. S.getCapturedRecordDecl()->field_begin();
  236. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  237. E = S.capture_end();
  238. I != E; ++I, ++Field) {
  239. if (I->capturesThis())
  240. CXXThisFieldDecl = *Field;
  241. else if (I->capturesVariable())
  242. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  243. else if (I->capturesVariableByCopy())
  244. CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
  245. }
  246. }
  247. virtual ~CGCapturedStmtInfo();
  248. CapturedRegionKind getKind() const { return Kind; }
  249. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  250. // \brief Retrieve the value of the context parameter.
  251. virtual llvm::Value *getContextValue() const { return ThisValue; }
  252. /// \brief Lookup the captured field decl for a variable.
  253. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  254. return CaptureFields.lookup(VD->getCanonicalDecl());
  255. }
  256. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  257. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  258. static bool classof(const CGCapturedStmtInfo *) {
  259. return true;
  260. }
  261. /// \brief Emit the captured statement body.
  262. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  263. CGF.incrementProfileCounter(S);
  264. CGF.EmitStmt(S);
  265. }
  266. /// \brief Get the name of the capture helper.
  267. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  268. private:
  269. /// \brief The kind of captured statement being generated.
  270. CapturedRegionKind Kind;
  271. /// \brief Keep the map between VarDecl and FieldDecl.
  272. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  273. /// \brief The base address of the captured record, passed in as the first
  274. /// argument of the parallel region function.
  275. llvm::Value *ThisValue;
  276. /// \brief Captured 'this' type.
  277. FieldDecl *CXXThisFieldDecl;
  278. };
  279. CGCapturedStmtInfo *CapturedStmtInfo;
  280. /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
  281. class CGCapturedStmtRAII {
  282. private:
  283. CodeGenFunction &CGF;
  284. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  285. public:
  286. CGCapturedStmtRAII(CodeGenFunction &CGF,
  287. CGCapturedStmtInfo *NewCapturedStmtInfo)
  288. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  289. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  290. }
  291. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  292. };
  293. /// An abstract representation of regular/ObjC call/message targets.
  294. class AbstractCallee {
  295. /// The function declaration of the callee.
  296. const Decl *CalleeDecl;
  297. public:
  298. AbstractCallee() : CalleeDecl(nullptr) {}
  299. AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
  300. AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
  301. bool hasFunctionDecl() const {
  302. return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
  303. }
  304. const Decl *getDecl() const { return CalleeDecl; }
  305. unsigned getNumParams() const {
  306. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  307. return FD->getNumParams();
  308. return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
  309. }
  310. const ParmVarDecl *getParamDecl(unsigned I) const {
  311. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
  312. return FD->getParamDecl(I);
  313. return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
  314. }
  315. };
  316. /// \brief Sanitizers enabled for this function.
  317. SanitizerSet SanOpts;
  318. /// \brief True if CodeGen currently emits code implementing sanitizer checks.
  319. bool IsSanitizerScope;
  320. /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  321. class SanitizerScope {
  322. CodeGenFunction *CGF;
  323. public:
  324. SanitizerScope(CodeGenFunction *CGF);
  325. ~SanitizerScope();
  326. };
  327. /// In C++, whether we are code generating a thunk. This controls whether we
  328. /// should emit cleanups.
  329. bool CurFuncIsThunk;
  330. /// In ARC, whether we should autorelease the return value.
  331. bool AutoreleaseResult;
  332. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  333. /// potentially set the return value.
  334. bool SawAsmBlock;
  335. const FunctionDecl *CurSEHParent = nullptr;
  336. /// True if the current function is an outlined SEH helper. This can be a
  337. /// finally block or filter expression.
  338. bool IsOutlinedSEHHelper;
  339. const CodeGen::CGBlockInfo *BlockInfo;
  340. llvm::Value *BlockPointer;
  341. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  342. FieldDecl *LambdaThisCaptureField;
  343. /// \brief A mapping from NRVO variables to the flags used to indicate
  344. /// when the NRVO has been applied to this variable.
  345. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  346. EHScopeStack EHStack;
  347. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  348. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  349. llvm::Instruction *CurrentFuncletPad = nullptr;
  350. class CallLifetimeEnd final : public EHScopeStack::Cleanup {
  351. llvm::Value *Addr;
  352. llvm::Value *Size;
  353. public:
  354. CallLifetimeEnd(Address addr, llvm::Value *size)
  355. : Addr(addr.getPointer()), Size(size) {}
  356. void Emit(CodeGenFunction &CGF, Flags flags) override {
  357. CGF.EmitLifetimeEnd(Size, Addr);
  358. }
  359. };
  360. /// Header for data within LifetimeExtendedCleanupStack.
  361. struct LifetimeExtendedCleanupHeader {
  362. /// The size of the following cleanup object.
  363. unsigned Size;
  364. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  365. CleanupKind Kind;
  366. size_t getSize() const { return Size; }
  367. CleanupKind getKind() const { return Kind; }
  368. };
  369. /// i32s containing the indexes of the cleanup destinations.
  370. llvm::AllocaInst *NormalCleanupDest;
  371. unsigned NextCleanupDestIndex;
  372. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  373. CGBlockInfo *FirstBlockInfo;
  374. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  375. llvm::BasicBlock *EHResumeBlock;
  376. /// The exception slot. All landing pads write the current exception pointer
  377. /// into this alloca.
  378. llvm::Value *ExceptionSlot;
  379. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  380. /// write the current selector value into this alloca.
  381. llvm::AllocaInst *EHSelectorSlot;
  382. /// A stack of exception code slots. Entering an __except block pushes a slot
  383. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  384. /// a value from the top of the stack.
  385. SmallVector<Address, 1> SEHCodeSlotStack;
  386. /// Value returned by __exception_info intrinsic.
  387. llvm::Value *SEHInfo = nullptr;
  388. /// Emits a landing pad for the current EH stack.
  389. llvm::BasicBlock *EmitLandingPad();
  390. llvm::BasicBlock *getInvokeDestImpl();
  391. template <class T>
  392. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  393. return DominatingValue<T>::save(*this, value);
  394. }
  395. public:
  396. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  397. /// rethrows.
  398. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  399. /// A class controlling the emission of a finally block.
  400. class FinallyInfo {
  401. /// Where the catchall's edge through the cleanup should go.
  402. JumpDest RethrowDest;
  403. /// A function to call to enter the catch.
  404. llvm::Constant *BeginCatchFn;
  405. /// An i1 variable indicating whether or not the @finally is
  406. /// running for an exception.
  407. llvm::AllocaInst *ForEHVar;
  408. /// An i8* variable into which the exception pointer to rethrow
  409. /// has been saved.
  410. llvm::AllocaInst *SavedExnVar;
  411. public:
  412. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  413. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  414. llvm::Constant *rethrowFn);
  415. void exit(CodeGenFunction &CGF);
  416. };
  417. /// Returns true inside SEH __try blocks.
  418. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  419. /// Returns true while emitting a cleanuppad.
  420. bool isCleanupPadScope() const {
  421. return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
  422. }
  423. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  424. /// current full-expression. Safe against the possibility that
  425. /// we're currently inside a conditionally-evaluated expression.
  426. template <class T, class... As>
  427. void pushFullExprCleanup(CleanupKind kind, As... A) {
  428. // If we're not in a conditional branch, or if none of the
  429. // arguments requires saving, then use the unconditional cleanup.
  430. if (!isInConditionalBranch())
  431. return EHStack.pushCleanup<T>(kind, A...);
  432. // Stash values in a tuple so we can guarantee the order of saves.
  433. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  434. SavedTuple Saved{saveValueInCond(A)...};
  435. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  436. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  437. initFullExprCleanup();
  438. }
  439. /// \brief Queue a cleanup to be pushed after finishing the current
  440. /// full-expression.
  441. template <class T, class... As>
  442. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  443. assert(!isInConditionalBranch() && "can't defer conditional cleanup");
  444. LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
  445. size_t OldSize = LifetimeExtendedCleanupStack.size();
  446. LifetimeExtendedCleanupStack.resize(
  447. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
  448. static_assert(sizeof(Header) % alignof(T) == 0,
  449. "Cleanup will be allocated on misaligned address");
  450. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  451. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  452. new (Buffer + sizeof(Header)) T(A...);
  453. }
  454. /// Set up the last cleaup that was pushed as a conditional
  455. /// full-expression cleanup.
  456. void initFullExprCleanup();
  457. /// PushDestructorCleanup - Push a cleanup to call the
  458. /// complete-object destructor of an object of the given type at the
  459. /// given address. Does nothing if T is not a C++ class type with a
  460. /// non-trivial destructor.
  461. void PushDestructorCleanup(QualType T, Address Addr);
  462. /// PushDestructorCleanup - Push a cleanup to call the
  463. /// complete-object variant of the given destructor on the object at
  464. /// the given address.
  465. void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
  466. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  467. /// process all branch fixups.
  468. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  469. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  470. /// The block cannot be reactivated. Pops it if it's the top of the
  471. /// stack.
  472. ///
  473. /// \param DominatingIP - An instruction which is known to
  474. /// dominate the current IP (if set) and which lies along
  475. /// all paths of execution between the current IP and the
  476. /// the point at which the cleanup comes into scope.
  477. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  478. llvm::Instruction *DominatingIP);
  479. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  480. /// Cannot be used to resurrect a deactivated cleanup.
  481. ///
  482. /// \param DominatingIP - An instruction which is known to
  483. /// dominate the current IP (if set) and which lies along
  484. /// all paths of execution between the current IP and the
  485. /// the point at which the cleanup comes into scope.
  486. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  487. llvm::Instruction *DominatingIP);
  488. /// \brief Enters a new scope for capturing cleanups, all of which
  489. /// will be executed once the scope is exited.
  490. class RunCleanupsScope {
  491. EHScopeStack::stable_iterator CleanupStackDepth;
  492. size_t LifetimeExtendedCleanupStackSize;
  493. bool OldDidCallStackSave;
  494. protected:
  495. bool PerformCleanup;
  496. private:
  497. RunCleanupsScope(const RunCleanupsScope &) = delete;
  498. void operator=(const RunCleanupsScope &) = delete;
  499. protected:
  500. CodeGenFunction& CGF;
  501. public:
  502. /// \brief Enter a new cleanup scope.
  503. explicit RunCleanupsScope(CodeGenFunction &CGF)
  504. : PerformCleanup(true), CGF(CGF)
  505. {
  506. CleanupStackDepth = CGF.EHStack.stable_begin();
  507. LifetimeExtendedCleanupStackSize =
  508. CGF.LifetimeExtendedCleanupStack.size();
  509. OldDidCallStackSave = CGF.DidCallStackSave;
  510. CGF.DidCallStackSave = false;
  511. }
  512. /// \brief Exit this cleanup scope, emitting any accumulated cleanups.
  513. ~RunCleanupsScope() {
  514. if (PerformCleanup)
  515. ForceCleanup();
  516. }
  517. /// \brief Determine whether this scope requires any cleanups.
  518. bool requiresCleanups() const {
  519. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  520. }
  521. /// \brief Force the emission of cleanups now, instead of waiting
  522. /// until this object is destroyed.
  523. /// \param ValuesToReload - A list of values that need to be available at
  524. /// the insertion point after cleanup emission. If cleanup emission created
  525. /// a shared cleanup block, these value pointers will be rewritten.
  526. /// Otherwise, they not will be modified.
  527. void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
  528. assert(PerformCleanup && "Already forced cleanup");
  529. CGF.DidCallStackSave = OldDidCallStackSave;
  530. CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
  531. ValuesToReload);
  532. PerformCleanup = false;
  533. }
  534. };
  535. class LexicalScope : public RunCleanupsScope {
  536. SourceRange Range;
  537. SmallVector<const LabelDecl*, 4> Labels;
  538. LexicalScope *ParentScope;
  539. LexicalScope(const LexicalScope &) = delete;
  540. void operator=(const LexicalScope &) = delete;
  541. public:
  542. /// \brief Enter a new cleanup scope.
  543. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  544. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  545. CGF.CurLexicalScope = this;
  546. if (CGDebugInfo *DI = CGF.getDebugInfo())
  547. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  548. }
  549. void addLabel(const LabelDecl *label) {
  550. assert(PerformCleanup && "adding label to dead scope?");
  551. Labels.push_back(label);
  552. }
  553. /// \brief Exit this cleanup scope, emitting any accumulated
  554. /// cleanups.
  555. ~LexicalScope() {
  556. if (CGDebugInfo *DI = CGF.getDebugInfo())
  557. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  558. // If we should perform a cleanup, force them now. Note that
  559. // this ends the cleanup scope before rescoping any labels.
  560. if (PerformCleanup) {
  561. ApplyDebugLocation DL(CGF, Range.getEnd());
  562. ForceCleanup();
  563. }
  564. }
  565. /// \brief Force the emission of cleanups now, instead of waiting
  566. /// until this object is destroyed.
  567. void ForceCleanup() {
  568. CGF.CurLexicalScope = ParentScope;
  569. RunCleanupsScope::ForceCleanup();
  570. if (!Labels.empty())
  571. rescopeLabels();
  572. }
  573. bool hasLabels() const {
  574. return !Labels.empty();
  575. }
  576. void rescopeLabels();
  577. };
  578. typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
  579. /// \brief The scope used to remap some variables as private in the OpenMP
  580. /// loop body (or other captured region emitted without outlining), and to
  581. /// restore old vars back on exit.
  582. class OMPPrivateScope : public RunCleanupsScope {
  583. DeclMapTy SavedLocals;
  584. DeclMapTy SavedPrivates;
  585. private:
  586. OMPPrivateScope(const OMPPrivateScope &) = delete;
  587. void operator=(const OMPPrivateScope &) = delete;
  588. public:
  589. /// \brief Enter a new OpenMP private scope.
  590. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  591. /// \brief Registers \a LocalVD variable as a private and apply \a
  592. /// PrivateGen function for it to generate corresponding private variable.
  593. /// \a PrivateGen returns an address of the generated private variable.
  594. /// \return true if the variable is registered as private, false if it has
  595. /// been privatized already.
  596. bool
  597. addPrivate(const VarDecl *LocalVD,
  598. llvm::function_ref<Address()> PrivateGen) {
  599. assert(PerformCleanup && "adding private to dead scope");
  600. LocalVD = LocalVD->getCanonicalDecl();
  601. // Only save it once.
  602. if (SavedLocals.count(LocalVD)) return false;
  603. // Copy the existing local entry to SavedLocals.
  604. auto it = CGF.LocalDeclMap.find(LocalVD);
  605. if (it != CGF.LocalDeclMap.end()) {
  606. SavedLocals.insert({LocalVD, it->second});
  607. } else {
  608. SavedLocals.insert({LocalVD, Address::invalid()});
  609. }
  610. // Generate the private entry.
  611. Address Addr = PrivateGen();
  612. QualType VarTy = LocalVD->getType();
  613. if (VarTy->isReferenceType()) {
  614. Address Temp = CGF.CreateMemTemp(VarTy);
  615. CGF.Builder.CreateStore(Addr.getPointer(), Temp);
  616. Addr = Temp;
  617. }
  618. SavedPrivates.insert({LocalVD, Addr});
  619. return true;
  620. }
  621. /// \brief Privatizes local variables previously registered as private.
  622. /// Registration is separate from the actual privatization to allow
  623. /// initializers use values of the original variables, not the private one.
  624. /// This is important, for example, if the private variable is a class
  625. /// variable initialized by a constructor that references other private
  626. /// variables. But at initialization original variables must be used, not
  627. /// private copies.
  628. /// \return true if at least one variable was privatized, false otherwise.
  629. bool Privatize() {
  630. copyInto(SavedPrivates, CGF.LocalDeclMap);
  631. SavedPrivates.clear();
  632. return !SavedLocals.empty();
  633. }
  634. void ForceCleanup() {
  635. RunCleanupsScope::ForceCleanup();
  636. copyInto(SavedLocals, CGF.LocalDeclMap);
  637. SavedLocals.clear();
  638. }
  639. /// \brief Exit scope - all the mapped variables are restored.
  640. ~OMPPrivateScope() {
  641. if (PerformCleanup)
  642. ForceCleanup();
  643. }
  644. /// Checks if the global variable is captured in current function.
  645. bool isGlobalVarCaptured(const VarDecl *VD) const {
  646. VD = VD->getCanonicalDecl();
  647. return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
  648. }
  649. private:
  650. /// Copy all the entries in the source map over the corresponding
  651. /// entries in the destination, which must exist.
  652. static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
  653. for (auto &pair : src) {
  654. if (!pair.second.isValid()) {
  655. dest.erase(pair.first);
  656. continue;
  657. }
  658. auto it = dest.find(pair.first);
  659. if (it != dest.end()) {
  660. it->second = pair.second;
  661. } else {
  662. dest.insert(pair);
  663. }
  664. }
  665. }
  666. };
  667. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  668. /// that have been added.
  669. void
  670. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  671. std::initializer_list<llvm::Value **> ValuesToReload = {});
  672. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  673. /// that have been added, then adds all lifetime-extended cleanups from
  674. /// the given position to the stack.
  675. void
  676. PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  677. size_t OldLifetimeExtendedStackSize,
  678. std::initializer_list<llvm::Value **> ValuesToReload = {});
  679. void ResolveBranchFixups(llvm::BasicBlock *Target);
  680. /// The given basic block lies in the current EH scope, but may be a
  681. /// target of a potentially scope-crossing jump; get a stable handle
  682. /// to which we can perform this jump later.
  683. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  684. return JumpDest(Target,
  685. EHStack.getInnermostNormalCleanup(),
  686. NextCleanupDestIndex++);
  687. }
  688. /// The given basic block lies in the current EH scope, but may be a
  689. /// target of a potentially scope-crossing jump; get a stable handle
  690. /// to which we can perform this jump later.
  691. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  692. return getJumpDestInCurrentScope(createBasicBlock(Name));
  693. }
  694. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  695. /// block through the normal cleanup handling code (if any) and then
  696. /// on to \arg Dest.
  697. void EmitBranchThroughCleanup(JumpDest Dest);
  698. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  699. /// specified destination obviously has no cleanups to run. 'false' is always
  700. /// a conservatively correct answer for this method.
  701. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  702. /// popCatchScope - Pops the catch scope at the top of the EHScope
  703. /// stack, emitting any required code (other than the catch handlers
  704. /// themselves).
  705. void popCatchScope();
  706. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  707. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  708. llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
  709. /// An object to manage conditionally-evaluated expressions.
  710. class ConditionalEvaluation {
  711. llvm::BasicBlock *StartBB;
  712. public:
  713. ConditionalEvaluation(CodeGenFunction &CGF)
  714. : StartBB(CGF.Builder.GetInsertBlock()) {}
  715. void begin(CodeGenFunction &CGF) {
  716. assert(CGF.OutermostConditional != this);
  717. if (!CGF.OutermostConditional)
  718. CGF.OutermostConditional = this;
  719. }
  720. void end(CodeGenFunction &CGF) {
  721. assert(CGF.OutermostConditional != nullptr);
  722. if (CGF.OutermostConditional == this)
  723. CGF.OutermostConditional = nullptr;
  724. }
  725. /// Returns a block which will be executed prior to each
  726. /// evaluation of the conditional code.
  727. llvm::BasicBlock *getStartingBlock() const {
  728. return StartBB;
  729. }
  730. };
  731. /// isInConditionalBranch - Return true if we're currently emitting
  732. /// one branch or the other of a conditional expression.
  733. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  734. void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
  735. assert(isInConditionalBranch());
  736. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  737. auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
  738. store->setAlignment(addr.getAlignment().getQuantity());
  739. }
  740. /// An RAII object to record that we're evaluating a statement
  741. /// expression.
  742. class StmtExprEvaluation {
  743. CodeGenFunction &CGF;
  744. /// We have to save the outermost conditional: cleanups in a
  745. /// statement expression aren't conditional just because the
  746. /// StmtExpr is.
  747. ConditionalEvaluation *SavedOutermostConditional;
  748. public:
  749. StmtExprEvaluation(CodeGenFunction &CGF)
  750. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  751. CGF.OutermostConditional = nullptr;
  752. }
  753. ~StmtExprEvaluation() {
  754. CGF.OutermostConditional = SavedOutermostConditional;
  755. CGF.EnsureInsertPoint();
  756. }
  757. };
  758. /// An object which temporarily prevents a value from being
  759. /// destroyed by aggressive peephole optimizations that assume that
  760. /// all uses of a value have been realized in the IR.
  761. class PeepholeProtection {
  762. llvm::Instruction *Inst;
  763. friend class CodeGenFunction;
  764. public:
  765. PeepholeProtection() : Inst(nullptr) {}
  766. };
  767. /// A non-RAII class containing all the information about a bound
  768. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  769. /// this which makes individual mappings very simple; using this
  770. /// class directly is useful when you have a variable number of
  771. /// opaque values or don't want the RAII functionality for some
  772. /// reason.
  773. class OpaqueValueMappingData {
  774. const OpaqueValueExpr *OpaqueValue;
  775. bool BoundLValue;
  776. CodeGenFunction::PeepholeProtection Protection;
  777. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  778. bool boundLValue)
  779. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  780. public:
  781. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  782. static bool shouldBindAsLValue(const Expr *expr) {
  783. // gl-values should be bound as l-values for obvious reasons.
  784. // Records should be bound as l-values because IR generation
  785. // always keeps them in memory. Expressions of function type
  786. // act exactly like l-values but are formally required to be
  787. // r-values in C.
  788. return expr->isGLValue() ||
  789. expr->getType()->isFunctionType() ||
  790. hasAggregateEvaluationKind(expr->getType());
  791. }
  792. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  793. const OpaqueValueExpr *ov,
  794. const Expr *e) {
  795. if (shouldBindAsLValue(ov))
  796. return bind(CGF, ov, CGF.EmitLValue(e));
  797. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  798. }
  799. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  800. const OpaqueValueExpr *ov,
  801. const LValue &lv) {
  802. assert(shouldBindAsLValue(ov));
  803. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  804. return OpaqueValueMappingData(ov, true);
  805. }
  806. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  807. const OpaqueValueExpr *ov,
  808. const RValue &rv) {
  809. assert(!shouldBindAsLValue(ov));
  810. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  811. OpaqueValueMappingData data(ov, false);
  812. // Work around an extremely aggressive peephole optimization in
  813. // EmitScalarConversion which assumes that all other uses of a
  814. // value are extant.
  815. data.Protection = CGF.protectFromPeepholes(rv);
  816. return data;
  817. }
  818. bool isValid() const { return OpaqueValue != nullptr; }
  819. void clear() { OpaqueValue = nullptr; }
  820. void unbind(CodeGenFunction &CGF) {
  821. assert(OpaqueValue && "no data to unbind!");
  822. if (BoundLValue) {
  823. CGF.OpaqueLValues.erase(OpaqueValue);
  824. } else {
  825. CGF.OpaqueRValues.erase(OpaqueValue);
  826. CGF.unprotectFromPeepholes(Protection);
  827. }
  828. }
  829. };
  830. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  831. class OpaqueValueMapping {
  832. CodeGenFunction &CGF;
  833. OpaqueValueMappingData Data;
  834. public:
  835. static bool shouldBindAsLValue(const Expr *expr) {
  836. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  837. }
  838. /// Build the opaque value mapping for the given conditional
  839. /// operator if it's the GNU ?: extension. This is a common
  840. /// enough pattern that the convenience operator is really
  841. /// helpful.
  842. ///
  843. OpaqueValueMapping(CodeGenFunction &CGF,
  844. const AbstractConditionalOperator *op) : CGF(CGF) {
  845. if (isa<ConditionalOperator>(op))
  846. // Leave Data empty.
  847. return;
  848. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  849. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  850. e->getCommon());
  851. }
  852. /// Build the opaque value mapping for an OpaqueValueExpr whose source
  853. /// expression is set to the expression the OVE represents.
  854. OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
  855. : CGF(CGF) {
  856. if (OV) {
  857. assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
  858. "for OVE with no source expression");
  859. Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
  860. }
  861. }
  862. OpaqueValueMapping(CodeGenFunction &CGF,
  863. const OpaqueValueExpr *opaqueValue,
  864. LValue lvalue)
  865. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  866. }
  867. OpaqueValueMapping(CodeGenFunction &CGF,
  868. const OpaqueValueExpr *opaqueValue,
  869. RValue rvalue)
  870. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  871. }
  872. void pop() {
  873. Data.unbind(CGF);
  874. Data.clear();
  875. }
  876. ~OpaqueValueMapping() {
  877. if (Data.isValid()) Data.unbind(CGF);
  878. }
  879. };
  880. private:
  881. CGDebugInfo *DebugInfo;
  882. bool DisableDebugInfo;
  883. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  884. /// calling llvm.stacksave for multiple VLAs in the same scope.
  885. bool DidCallStackSave;
  886. /// IndirectBranch - The first time an indirect goto is seen we create a block
  887. /// with an indirect branch. Every time we see the address of a label taken,
  888. /// we add the label to the indirect goto. Every subsequent indirect goto is
  889. /// codegen'd as a jump to the IndirectBranch's basic block.
  890. llvm::IndirectBrInst *IndirectBranch;
  891. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  892. /// decls.
  893. DeclMapTy LocalDeclMap;
  894. /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
  895. /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
  896. /// parameter.
  897. llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
  898. SizeArguments;
  899. /// Track escaped local variables with auto storage. Used during SEH
  900. /// outlining to produce a call to llvm.localescape.
  901. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  902. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  903. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  904. // BreakContinueStack - This keeps track of where break and continue
  905. // statements should jump to.
  906. struct BreakContinue {
  907. BreakContinue(JumpDest Break, JumpDest Continue)
  908. : BreakBlock(Break), ContinueBlock(Continue) {}
  909. JumpDest BreakBlock;
  910. JumpDest ContinueBlock;
  911. };
  912. SmallVector<BreakContinue, 8> BreakContinueStack;
  913. /// Handles cancellation exit points in OpenMP-related constructs.
  914. class OpenMPCancelExitStack {
  915. /// Tracks cancellation exit point and join point for cancel-related exit
  916. /// and normal exit.
  917. struct CancelExit {
  918. CancelExit() = default;
  919. CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
  920. JumpDest ContBlock)
  921. : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
  922. OpenMPDirectiveKind Kind = OMPD_unknown;
  923. /// true if the exit block has been emitted already by the special
  924. /// emitExit() call, false if the default codegen is used.
  925. bool HasBeenEmitted = false;
  926. JumpDest ExitBlock;
  927. JumpDest ContBlock;
  928. };
  929. SmallVector<CancelExit, 8> Stack;
  930. public:
  931. OpenMPCancelExitStack() : Stack(1) {}
  932. ~OpenMPCancelExitStack() = default;
  933. /// Fetches the exit block for the current OpenMP construct.
  934. JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
  935. /// Emits exit block with special codegen procedure specific for the related
  936. /// OpenMP construct + emits code for normal construct cleanup.
  937. void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  938. const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
  939. if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
  940. assert(CGF.getOMPCancelDestination(Kind).isValid());
  941. assert(CGF.HaveInsertPoint());
  942. assert(!Stack.back().HasBeenEmitted);
  943. auto IP = CGF.Builder.saveAndClearIP();
  944. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  945. CodeGen(CGF);
  946. CGF.EmitBranch(Stack.back().ContBlock.getBlock());
  947. CGF.Builder.restoreIP(IP);
  948. Stack.back().HasBeenEmitted = true;
  949. }
  950. CodeGen(CGF);
  951. }
  952. /// Enter the cancel supporting \a Kind construct.
  953. /// \param Kind OpenMP directive that supports cancel constructs.
  954. /// \param HasCancel true, if the construct has inner cancel directive,
  955. /// false otherwise.
  956. void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
  957. Stack.push_back({Kind,
  958. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
  959. : JumpDest(),
  960. HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
  961. : JumpDest()});
  962. }
  963. /// Emits default exit point for the cancel construct (if the special one
  964. /// has not be used) + join point for cancel/normal exits.
  965. void exit(CodeGenFunction &CGF) {
  966. if (getExitBlock().isValid()) {
  967. assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
  968. bool HaveIP = CGF.HaveInsertPoint();
  969. if (!Stack.back().HasBeenEmitted) {
  970. if (HaveIP)
  971. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  972. CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
  973. CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
  974. }
  975. CGF.EmitBlock(Stack.back().ContBlock.getBlock());
  976. if (!HaveIP) {
  977. CGF.Builder.CreateUnreachable();
  978. CGF.Builder.ClearInsertionPoint();
  979. }
  980. }
  981. Stack.pop_back();
  982. }
  983. };
  984. OpenMPCancelExitStack OMPCancelStack;
  985. CodeGenPGO PGO;
  986. /// Calculate branch weights appropriate for PGO data
  987. llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
  988. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
  989. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  990. uint64_t LoopCount);
  991. public:
  992. /// Increment the profiler's counter for the given statement by \p StepV.
  993. /// If \p StepV is null, the default increment is 1.
  994. void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
  995. if (CGM.getCodeGenOpts().hasProfileClangInstr())
  996. PGO.emitCounterIncrement(Builder, S, StepV);
  997. PGO.setCurrentStmt(S);
  998. }
  999. /// Get the profiler's count for the given statement.
  1000. uint64_t getProfileCount(const Stmt *S) {
  1001. Optional<uint64_t> Count = PGO.getStmtCount(S);
  1002. if (!Count.hasValue())
  1003. return 0;
  1004. return *Count;
  1005. }
  1006. /// Set the profiler's current count.
  1007. void setCurrentProfileCount(uint64_t Count) {
  1008. PGO.setCurrentRegionCount(Count);
  1009. }
  1010. /// Get the profiler's current count. This is generally the count for the most
  1011. /// recently incremented counter.
  1012. uint64_t getCurrentProfileCount() {
  1013. return PGO.getCurrentRegionCount();
  1014. }
  1015. private:
  1016. /// SwitchInsn - This is nearest current switch instruction. It is null if
  1017. /// current context is not in a switch.
  1018. llvm::SwitchInst *SwitchInsn;
  1019. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  1020. SmallVector<uint64_t, 16> *SwitchWeights;
  1021. /// CaseRangeBlock - This block holds if condition check for last case
  1022. /// statement range in current switch instruction.
  1023. llvm::BasicBlock *CaseRangeBlock;
  1024. /// OpaqueLValues - Keeps track of the current set of opaque value
  1025. /// expressions.
  1026. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  1027. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  1028. // VLASizeMap - This keeps track of the associated size for each VLA type.
  1029. // We track this by the size expression rather than the type itself because
  1030. // in certain situations, like a const qualifier applied to an VLA typedef,
  1031. // multiple VLA types can share the same size expression.
  1032. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  1033. // enter/leave scopes.
  1034. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  1035. /// A block containing a single 'unreachable' instruction. Created
  1036. /// lazily by getUnreachableBlock().
  1037. llvm::BasicBlock *UnreachableBlock;
  1038. /// Counts of the number return expressions in the function.
  1039. unsigned NumReturnExprs;
  1040. /// Count the number of simple (constant) return expressions in the function.
  1041. unsigned NumSimpleReturnExprs;
  1042. /// The last regular (non-return) debug location (breakpoint) in the function.
  1043. SourceLocation LastStopPoint;
  1044. public:
  1045. /// A scope within which we are constructing the fields of an object which
  1046. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  1047. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  1048. class FieldConstructionScope {
  1049. public:
  1050. FieldConstructionScope(CodeGenFunction &CGF, Address This)
  1051. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  1052. CGF.CXXDefaultInitExprThis = This;
  1053. }
  1054. ~FieldConstructionScope() {
  1055. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  1056. }
  1057. private:
  1058. CodeGenFunction &CGF;
  1059. Address OldCXXDefaultInitExprThis;
  1060. };
  1061. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  1062. /// is overridden to be the object under construction.
  1063. class CXXDefaultInitExprScope {
  1064. public:
  1065. CXXDefaultInitExprScope(CodeGenFunction &CGF)
  1066. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
  1067. OldCXXThisAlignment(CGF.CXXThisAlignment) {
  1068. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
  1069. CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
  1070. }
  1071. ~CXXDefaultInitExprScope() {
  1072. CGF.CXXThisValue = OldCXXThisValue;
  1073. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1074. }
  1075. public:
  1076. CodeGenFunction &CGF;
  1077. llvm::Value *OldCXXThisValue;
  1078. CharUnits OldCXXThisAlignment;
  1079. };
  1080. /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
  1081. /// current loop index is overridden.
  1082. class ArrayInitLoopExprScope {
  1083. public:
  1084. ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
  1085. : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
  1086. CGF.ArrayInitIndex = Index;
  1087. }
  1088. ~ArrayInitLoopExprScope() {
  1089. CGF.ArrayInitIndex = OldArrayInitIndex;
  1090. }
  1091. private:
  1092. CodeGenFunction &CGF;
  1093. llvm::Value *OldArrayInitIndex;
  1094. };
  1095. class InlinedInheritingConstructorScope {
  1096. public:
  1097. InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
  1098. : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
  1099. OldCurCodeDecl(CGF.CurCodeDecl),
  1100. OldCXXABIThisDecl(CGF.CXXABIThisDecl),
  1101. OldCXXABIThisValue(CGF.CXXABIThisValue),
  1102. OldCXXThisValue(CGF.CXXThisValue),
  1103. OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
  1104. OldCXXThisAlignment(CGF.CXXThisAlignment),
  1105. OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
  1106. OldCXXInheritedCtorInitExprArgs(
  1107. std::move(CGF.CXXInheritedCtorInitExprArgs)) {
  1108. CGF.CurGD = GD;
  1109. CGF.CurFuncDecl = CGF.CurCodeDecl =
  1110. cast<CXXConstructorDecl>(GD.getDecl());
  1111. CGF.CXXABIThisDecl = nullptr;
  1112. CGF.CXXABIThisValue = nullptr;
  1113. CGF.CXXThisValue = nullptr;
  1114. CGF.CXXABIThisAlignment = CharUnits();
  1115. CGF.CXXThisAlignment = CharUnits();
  1116. CGF.ReturnValue = Address::invalid();
  1117. CGF.FnRetTy = QualType();
  1118. CGF.CXXInheritedCtorInitExprArgs.clear();
  1119. }
  1120. ~InlinedInheritingConstructorScope() {
  1121. CGF.CurGD = OldCurGD;
  1122. CGF.CurFuncDecl = OldCurFuncDecl;
  1123. CGF.CurCodeDecl = OldCurCodeDecl;
  1124. CGF.CXXABIThisDecl = OldCXXABIThisDecl;
  1125. CGF.CXXABIThisValue = OldCXXABIThisValue;
  1126. CGF.CXXThisValue = OldCXXThisValue;
  1127. CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
  1128. CGF.CXXThisAlignment = OldCXXThisAlignment;
  1129. CGF.ReturnValue = OldReturnValue;
  1130. CGF.FnRetTy = OldFnRetTy;
  1131. CGF.CXXInheritedCtorInitExprArgs =
  1132. std::move(OldCXXInheritedCtorInitExprArgs);
  1133. }
  1134. private:
  1135. CodeGenFunction &CGF;
  1136. GlobalDecl OldCurGD;
  1137. const Decl *OldCurFuncDecl;
  1138. const Decl *OldCurCodeDecl;
  1139. ImplicitParamDecl *OldCXXABIThisDecl;
  1140. llvm::Value *OldCXXABIThisValue;
  1141. llvm::Value *OldCXXThisValue;
  1142. CharUnits OldCXXABIThisAlignment;
  1143. CharUnits OldCXXThisAlignment;
  1144. Address OldReturnValue;
  1145. QualType OldFnRetTy;
  1146. CallArgList OldCXXInheritedCtorInitExprArgs;
  1147. };
  1148. private:
  1149. /// CXXThisDecl - When generating code for a C++ member function,
  1150. /// this will hold the implicit 'this' declaration.
  1151. ImplicitParamDecl *CXXABIThisDecl;
  1152. llvm::Value *CXXABIThisValue;
  1153. llvm::Value *CXXThisValue;
  1154. CharUnits CXXABIThisAlignment;
  1155. CharUnits CXXThisAlignment;
  1156. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  1157. /// this expression.
  1158. Address CXXDefaultInitExprThis = Address::invalid();
  1159. /// The current array initialization index when evaluating an
  1160. /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
  1161. llvm::Value *ArrayInitIndex = nullptr;
  1162. /// The values of function arguments to use when evaluating
  1163. /// CXXInheritedCtorInitExprs within this context.
  1164. CallArgList CXXInheritedCtorInitExprArgs;
  1165. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  1166. /// destructor, this will hold the implicit argument (e.g. VTT).
  1167. ImplicitParamDecl *CXXStructorImplicitParamDecl;
  1168. llvm::Value *CXXStructorImplicitParamValue;
  1169. /// OutermostConditional - Points to the outermost active
  1170. /// conditional control. This is used so that we know if a
  1171. /// temporary should be destroyed conditionally.
  1172. ConditionalEvaluation *OutermostConditional;
  1173. /// The current lexical scope.
  1174. LexicalScope *CurLexicalScope;
  1175. /// The current source location that should be used for exception
  1176. /// handling code.
  1177. SourceLocation CurEHLocation;
  1178. /// BlockByrefInfos - For each __block variable, contains
  1179. /// information about the layout of the variable.
  1180. llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
  1181. /// Used by -fsanitize=nullability-return to determine whether the return
  1182. /// value can be checked.
  1183. llvm::Value *RetValNullabilityPrecondition = nullptr;
  1184. /// Check if -fsanitize=nullability-return instrumentation is required for
  1185. /// this function.
  1186. bool requiresReturnValueNullabilityCheck() const {
  1187. return RetValNullabilityPrecondition;
  1188. }
  1189. /// Used to store precise source locations for return statements by the
  1190. /// runtime return value checks.
  1191. Address ReturnLocation = Address::invalid();
  1192. /// Check if the return value of this function requires sanitization.
  1193. bool requiresReturnValueCheck() const {
  1194. return requiresReturnValueNullabilityCheck() ||
  1195. (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  1196. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>());
  1197. }
  1198. llvm::BasicBlock *TerminateLandingPad;
  1199. llvm::BasicBlock *TerminateHandler;
  1200. llvm::BasicBlock *TrapBB;
  1201. /// True if we need emit the life-time markers.
  1202. const bool ShouldEmitLifetimeMarkers;
  1203. /// Add OpenCL kernel arg metadata and the kernel attribute meatadata to
  1204. /// the function metadata.
  1205. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  1206. llvm::Function *Fn);
  1207. public:
  1208. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  1209. ~CodeGenFunction();
  1210. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  1211. ASTContext &getContext() const { return CGM.getContext(); }
  1212. CGDebugInfo *getDebugInfo() {
  1213. if (DisableDebugInfo)
  1214. return nullptr;
  1215. return DebugInfo;
  1216. }
  1217. void disableDebugInfo() { DisableDebugInfo = true; }
  1218. void enableDebugInfo() { DisableDebugInfo = false; }
  1219. bool shouldUseFusedARCCalls() {
  1220. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1221. }
  1222. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1223. /// Returns a pointer to the function's exception object and selector slot,
  1224. /// which is assigned in every landing pad.
  1225. Address getExceptionSlot();
  1226. Address getEHSelectorSlot();
  1227. /// Returns the contents of the function's exception object and selector
  1228. /// slots.
  1229. llvm::Value *getExceptionFromSlot();
  1230. llvm::Value *getSelectorFromSlot();
  1231. Address getNormalCleanupDestSlot();
  1232. llvm::BasicBlock *getUnreachableBlock() {
  1233. if (!UnreachableBlock) {
  1234. UnreachableBlock = createBasicBlock("unreachable");
  1235. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1236. }
  1237. return UnreachableBlock;
  1238. }
  1239. llvm::BasicBlock *getInvokeDest() {
  1240. if (!EHStack.requiresLandingPad()) return nullptr;
  1241. return getInvokeDestImpl();
  1242. }
  1243. bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
  1244. const TargetInfo &getTarget() const { return Target; }
  1245. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1246. const TargetCodeGenInfo &getTargetHooks() const {
  1247. return CGM.getTargetCodeGenInfo();
  1248. }
  1249. //===--------------------------------------------------------------------===//
  1250. // Cleanups
  1251. //===--------------------------------------------------------------------===//
  1252. typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
  1253. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1254. Address arrayEndPointer,
  1255. QualType elementType,
  1256. CharUnits elementAlignment,
  1257. Destroyer *destroyer);
  1258. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1259. llvm::Value *arrayEnd,
  1260. QualType elementType,
  1261. CharUnits elementAlignment,
  1262. Destroyer *destroyer);
  1263. void pushDestroy(QualType::DestructionKind dtorKind,
  1264. Address addr, QualType type);
  1265. void pushEHDestroy(QualType::DestructionKind dtorKind,
  1266. Address addr, QualType type);
  1267. void pushDestroy(CleanupKind kind, Address addr, QualType type,
  1268. Destroyer *destroyer, bool useEHCleanupForArray);
  1269. void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
  1270. QualType type, Destroyer *destroyer,
  1271. bool useEHCleanupForArray);
  1272. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  1273. llvm::Value *CompletePtr,
  1274. QualType ElementType);
  1275. void pushStackRestore(CleanupKind kind, Address SPMem);
  1276. void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
  1277. bool useEHCleanupForArray);
  1278. llvm::Function *generateDestroyHelper(Address addr, QualType type,
  1279. Destroyer *destroyer,
  1280. bool useEHCleanupForArray,
  1281. const VarDecl *VD);
  1282. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1283. QualType elementType, CharUnits elementAlign,
  1284. Destroyer *destroyer,
  1285. bool checkZeroLength, bool useEHCleanup);
  1286. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1287. /// Determines whether an EH cleanup is required to destroy a type
  1288. /// with the given destruction kind.
  1289. bool needsEHCleanup(QualType::DestructionKind kind) {
  1290. switch (kind) {
  1291. case QualType::DK_none:
  1292. return false;
  1293. case QualType::DK_cxx_destructor:
  1294. case QualType::DK_objc_weak_lifetime:
  1295. return getLangOpts().Exceptions;
  1296. case QualType::DK_objc_strong_lifetime:
  1297. return getLangOpts().Exceptions &&
  1298. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1299. }
  1300. llvm_unreachable("bad destruction kind");
  1301. }
  1302. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1303. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1304. }
  1305. //===--------------------------------------------------------------------===//
  1306. // Objective-C
  1307. //===--------------------------------------------------------------------===//
  1308. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1309. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1310. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1311. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1312. const ObjCPropertyImplDecl *PID);
  1313. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1314. const ObjCPropertyImplDecl *propImpl,
  1315. const ObjCMethodDecl *GetterMothodDecl,
  1316. llvm::Constant *AtomicHelperFn);
  1317. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1318. ObjCMethodDecl *MD, bool ctor);
  1319. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1320. /// for the given property.
  1321. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1322. const ObjCPropertyImplDecl *PID);
  1323. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1324. const ObjCPropertyImplDecl *propImpl,
  1325. llvm::Constant *AtomicHelperFn);
  1326. //===--------------------------------------------------------------------===//
  1327. // Block Bits
  1328. //===--------------------------------------------------------------------===//
  1329. /// Emit block literal.
  1330. /// \return an LLVM value which is a pointer to a struct which contains
  1331. /// information about the block, including the block invoke function, the
  1332. /// captured variables, etc.
  1333. /// \param InvokeF will contain the block invoke function if it is not
  1334. /// nullptr.
  1335. llvm::Value *EmitBlockLiteral(const BlockExpr *,
  1336. llvm::Function **InvokeF = nullptr);
  1337. static void destroyBlockInfos(CGBlockInfo *info);
  1338. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1339. const CGBlockInfo &Info,
  1340. const DeclMapTy &ldm,
  1341. bool IsLambdaConversionToBlock,
  1342. bool BuildGlobalBlock);
  1343. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1344. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1345. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1346. const ObjCPropertyImplDecl *PID);
  1347. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1348. const ObjCPropertyImplDecl *PID);
  1349. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1350. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1351. class AutoVarEmission;
  1352. void emitByrefStructureInit(const AutoVarEmission &emission);
  1353. void enterByrefCleanup(const AutoVarEmission &emission);
  1354. void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
  1355. llvm::Value *ptr);
  1356. Address LoadBlockStruct();
  1357. Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1358. /// BuildBlockByrefAddress - Computes the location of the
  1359. /// data in a variable which is declared as __block.
  1360. Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
  1361. bool followForward = true);
  1362. Address emitBlockByrefAddress(Address baseAddr,
  1363. const BlockByrefInfo &info,
  1364. bool followForward,
  1365. const llvm::Twine &name);
  1366. const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
  1367. QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
  1368. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1369. const CGFunctionInfo &FnInfo);
  1370. /// \brief Emit code for the start of a function.
  1371. /// \param Loc The location to be associated with the function.
  1372. /// \param StartLoc The location of the function body.
  1373. void StartFunction(GlobalDecl GD,
  1374. QualType RetTy,
  1375. llvm::Function *Fn,
  1376. const CGFunctionInfo &FnInfo,
  1377. const FunctionArgList &Args,
  1378. SourceLocation Loc = SourceLocation(),
  1379. SourceLocation StartLoc = SourceLocation());
  1380. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
  1381. void EmitConstructorBody(FunctionArgList &Args);
  1382. void EmitDestructorBody(FunctionArgList &Args);
  1383. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1384. void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
  1385. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1386. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1387. CallArgList &CallArgs);
  1388. void EmitLambdaBlockInvokeBody();
  1389. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1390. void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
  1391. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1392. /// \brief Emit the unified return block, trying to avoid its emission when
  1393. /// possible.
  1394. /// \return The debug location of the user written return statement if the
  1395. /// return block is is avoided.
  1396. llvm::DebugLoc EmitReturnBlock();
  1397. /// FinishFunction - Complete IR generation of the current function. It is
  1398. /// legal to call this function even if there is no current insertion point.
  1399. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1400. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1401. const CGFunctionInfo &FnInfo);
  1402. void EmitCallAndReturnForThunk(llvm::Constant *Callee,
  1403. const ThunkInfo *Thunk);
  1404. void FinishThunk();
  1405. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1406. void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
  1407. llvm::Value *Callee);
  1408. /// Generate a thunk for the given method.
  1409. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1410. GlobalDecl GD, const ThunkInfo &Thunk);
  1411. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1412. const CGFunctionInfo &FnInfo,
  1413. GlobalDecl GD, const ThunkInfo &Thunk);
  1414. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1415. FunctionArgList &Args);
  1416. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
  1417. /// Struct with all informations about dynamic [sub]class needed to set vptr.
  1418. struct VPtr {
  1419. BaseSubobject Base;
  1420. const CXXRecordDecl *NearestVBase;
  1421. CharUnits OffsetFromNearestVBase;
  1422. const CXXRecordDecl *VTableClass;
  1423. };
  1424. /// Initialize the vtable pointer of the given subobject.
  1425. void InitializeVTablePointer(const VPtr &vptr);
  1426. typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
  1427. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1428. VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
  1429. void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
  1430. CharUnits OffsetFromNearestVBase,
  1431. bool BaseIsNonVirtualPrimaryBase,
  1432. const CXXRecordDecl *VTableClass,
  1433. VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
  1434. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1435. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1436. /// to by This.
  1437. llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
  1438. const CXXRecordDecl *VTableClass);
  1439. enum CFITypeCheckKind {
  1440. CFITCK_VCall,
  1441. CFITCK_NVCall,
  1442. CFITCK_DerivedCast,
  1443. CFITCK_UnrelatedCast,
  1444. CFITCK_ICall,
  1445. };
  1446. /// \brief Derived is the presumed address of an object of type T after a
  1447. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1448. /// table for Derived belongs to a class derived from T.
  1449. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1450. bool MayBeNull, CFITypeCheckKind TCK,
  1451. SourceLocation Loc);
  1452. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1453. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1454. void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
  1455. CFITypeCheckKind TCK, SourceLocation Loc);
  1456. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1457. /// RD using llvm.type.test.
  1458. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1459. CFITypeCheckKind TCK, SourceLocation Loc);
  1460. /// If whole-program virtual table optimization is enabled, emit an assumption
  1461. /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
  1462. /// enabled, emit a check that VTable is a member of RD's type identifier.
  1463. void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  1464. llvm::Value *VTable, SourceLocation Loc);
  1465. /// Returns whether we should perform a type checked load when loading a
  1466. /// virtual function for virtual calls to members of RD. This is generally
  1467. /// true when both vcall CFI and whole-program-vtables are enabled.
  1468. bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
  1469. /// Emit a type checked load from the given vtable.
  1470. llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
  1471. uint64_t VTableByteOffset);
  1472. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1473. /// given phase of destruction for a destructor. The end result
  1474. /// should call destructors on members and base classes in reverse
  1475. /// order of their construction.
  1476. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1477. /// ShouldInstrumentFunction - Return true if the current function should be
  1478. /// instrumented with __cyg_profile_func_* calls
  1479. bool ShouldInstrumentFunction();
  1480. /// ShouldXRayInstrument - Return true if the current function should be
  1481. /// instrumented with XRay nop sleds.
  1482. bool ShouldXRayInstrumentFunction() const;
  1483. /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
  1484. /// XRay custom event handling calls.
  1485. bool AlwaysEmitXRayCustomEvents() const;
  1486. /// Encode an address into a form suitable for use in a function prologue.
  1487. llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
  1488. llvm::Constant *Addr);
  1489. /// Decode an address used in a function prologue, encoded by \c
  1490. /// EncodeAddrForUseInPrologue.
  1491. llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
  1492. llvm::Value *EncodedAddr);
  1493. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1494. /// arguments for the given function. This is also responsible for naming the
  1495. /// LLVM function arguments.
  1496. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1497. llvm::Function *Fn,
  1498. const FunctionArgList &Args);
  1499. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1500. /// given temporary.
  1501. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1502. SourceLocation EndLoc);
  1503. /// Emit a test that checks if the return value \p RV is nonnull.
  1504. void EmitReturnValueCheck(llvm::Value *RV);
  1505. /// EmitStartEHSpec - Emit the start of the exception spec.
  1506. void EmitStartEHSpec(const Decl *D);
  1507. /// EmitEndEHSpec - Emit the end of the exception spec.
  1508. void EmitEndEHSpec(const Decl *D);
  1509. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1510. llvm::BasicBlock *getTerminateLandingPad();
  1511. /// getTerminateHandler - Return a handler (not a landing pad, just
  1512. /// a catch handler) that just calls terminate. This is used when
  1513. /// a terminate scope encloses a try.
  1514. llvm::BasicBlock *getTerminateHandler();
  1515. llvm::Type *ConvertTypeForMem(QualType T);
  1516. llvm::Type *ConvertType(QualType T);
  1517. llvm::Type *ConvertType(const TypeDecl *T) {
  1518. return ConvertType(getContext().getTypeDeclType(T));
  1519. }
  1520. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1521. /// generating code for an Objective-C method.
  1522. llvm::Value *LoadObjCSelf();
  1523. /// TypeOfSelfObject - Return type of object that this self represents.
  1524. QualType TypeOfSelfObject();
  1525. /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
  1526. static TypeEvaluationKind getEvaluationKind(QualType T);
  1527. static bool hasScalarEvaluationKind(QualType T) {
  1528. return getEvaluationKind(T) == TEK_Scalar;
  1529. }
  1530. static bool hasAggregateEvaluationKind(QualType T) {
  1531. return getEvaluationKind(T) == TEK_Aggregate;
  1532. }
  1533. /// createBasicBlock - Create an LLVM basic block.
  1534. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1535. llvm::Function *parent = nullptr,
  1536. llvm::BasicBlock *before = nullptr) {
  1537. #ifdef NDEBUG
  1538. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1539. #else
  1540. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1541. #endif
  1542. }
  1543. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1544. /// label maps to.
  1545. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1546. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1547. /// another basic block, simplify it. This assumes that no other code could
  1548. /// potentially reference the basic block.
  1549. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1550. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1551. /// adding a fall-through branch from the current insert block if
  1552. /// necessary. It is legal to call this function even if there is no current
  1553. /// insertion point.
  1554. ///
  1555. /// IsFinished - If true, indicates that the caller has finished emitting
  1556. /// branches to the given block and does not expect to emit code into it. This
  1557. /// means the block can be ignored if it is unreachable.
  1558. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1559. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1560. /// near its uses, and leave the insertion point in it.
  1561. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1562. /// EmitBranch - Emit a branch to the specified basic block from the current
  1563. /// insert block, taking care to avoid creation of branches from dummy
  1564. /// blocks. It is legal to call this function even if there is no current
  1565. /// insertion point.
  1566. ///
  1567. /// This function clears the current insertion point. The caller should follow
  1568. /// calls to this function with calls to Emit*Block prior to generation new
  1569. /// code.
  1570. void EmitBranch(llvm::BasicBlock *Block);
  1571. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1572. /// indicates that the current code being emitted is unreachable.
  1573. bool HaveInsertPoint() const {
  1574. return Builder.GetInsertBlock() != nullptr;
  1575. }
  1576. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1577. /// emitted IR has a place to go. Note that by definition, if this function
  1578. /// creates a block then that block is unreachable; callers may do better to
  1579. /// detect when no insertion point is defined and simply skip IR generation.
  1580. void EnsureInsertPoint() {
  1581. if (!HaveInsertPoint())
  1582. EmitBlock(createBasicBlock());
  1583. }
  1584. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1585. /// specified stmt yet.
  1586. void ErrorUnsupported(const Stmt *S, const char *Type);
  1587. //===--------------------------------------------------------------------===//
  1588. // Helpers
  1589. //===--------------------------------------------------------------------===//
  1590. LValue MakeAddrLValue(Address Addr, QualType T,
  1591. AlignmentSource Source = AlignmentSource::Type) {
  1592. return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
  1593. CGM.getTBAAAccessInfo(T));
  1594. }
  1595. LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
  1596. TBAAAccessInfo TBAAInfo) {
  1597. return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
  1598. }
  1599. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1600. AlignmentSource Source = AlignmentSource::Type) {
  1601. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1602. LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
  1603. }
  1604. LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
  1605. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
  1606. return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
  1607. BaseInfo, TBAAInfo);
  1608. }
  1609. LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
  1610. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1611. CharUnits getNaturalTypeAlignment(QualType T,
  1612. LValueBaseInfo *BaseInfo = nullptr,
  1613. TBAAAccessInfo *TBAAInfo = nullptr,
  1614. bool forPointeeType = false);
  1615. CharUnits getNaturalPointeeTypeAlignment(QualType T,
  1616. LValueBaseInfo *BaseInfo = nullptr,
  1617. TBAAAccessInfo *TBAAInfo = nullptr);
  1618. Address EmitLoadOfReference(LValue RefLVal,
  1619. LValueBaseInfo *PointeeBaseInfo = nullptr,
  1620. TBAAAccessInfo *PointeeTBAAInfo = nullptr);
  1621. LValue EmitLoadOfReferenceLValue(LValue RefLVal);
  1622. LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
  1623. AlignmentSource Source =
  1624. AlignmentSource::Type) {
  1625. LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
  1626. CGM.getTBAAAccessInfo(RefTy));
  1627. return EmitLoadOfReferenceLValue(RefLVal);
  1628. }
  1629. Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
  1630. LValueBaseInfo *BaseInfo = nullptr,
  1631. TBAAAccessInfo *TBAAInfo = nullptr);
  1632. LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
  1633. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  1634. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  1635. /// insertion point of the builder. The caller is responsible for setting an
  1636. /// appropriate alignment on
  1637. /// the alloca.
  1638. ///
  1639. /// \p ArraySize is the number of array elements to be allocated if it
  1640. /// is not nullptr.
  1641. ///
  1642. /// LangAS::Default is the address space of pointers to local variables and
  1643. /// temporaries, as exposed in the source language. In certain
  1644. /// configurations, this is not the same as the alloca address space, and a
  1645. /// cast is needed to lift the pointer from the alloca AS into
  1646. /// LangAS::Default. This can happen when the target uses a restricted
  1647. /// address space for the stack but the source language requires
  1648. /// LangAS::Default to be a generic address space. The latter condition is
  1649. /// common for most programming languages; OpenCL is an exception in that
  1650. /// LangAS::Default is the private address space, which naturally maps
  1651. /// to the stack.
  1652. ///
  1653. /// Because the address of a temporary is often exposed to the program in
  1654. /// various ways, this function will perform the cast by default. The cast
  1655. /// may be avoided by passing false as \p CastToDefaultAddrSpace; this is
  1656. /// more efficient if the caller knows that the address will not be exposed.
  1657. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
  1658. llvm::Value *ArraySize = nullptr);
  1659. Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
  1660. const Twine &Name = "tmp",
  1661. llvm::Value *ArraySize = nullptr,
  1662. bool CastToDefaultAddrSpace = true);
  1663. /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
  1664. /// default ABI alignment of the given LLVM type.
  1665. ///
  1666. /// IMPORTANT NOTE: This is *not* generally the right alignment for
  1667. /// any given AST type that happens to have been lowered to the
  1668. /// given IR type. This should only ever be used for function-local,
  1669. /// IR-driven manipulations like saving and restoring a value. Do
  1670. /// not hand this address off to arbitrary IRGen routines, and especially
  1671. /// do not pass it as an argument to a function that might expect a
  1672. /// properly ABI-aligned value.
  1673. Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  1674. const Twine &Name = "tmp");
  1675. /// InitTempAlloca - Provide an initial value for the given alloca which
  1676. /// will be observable at all locations in the function.
  1677. ///
  1678. /// The address should be something that was returned from one of
  1679. /// the CreateTempAlloca or CreateMemTemp routines, and the
  1680. /// initializer must be valid in the entry block (i.e. it must
  1681. /// either be a constant or an argument value).
  1682. void InitTempAlloca(Address Alloca, llvm::Value *Value);
  1683. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1684. /// appropriate alignment. This routine should only be used when an temporary
  1685. /// value needs to be stored into an alloca (for example, to avoid explicit
  1686. /// PHI construction), but the type is the IR type, not the type appropriate
  1687. /// for storing in memory.
  1688. ///
  1689. /// That is, this is exactly equivalent to CreateMemTemp, but calling
  1690. /// ConvertType instead of ConvertTypeForMem.
  1691. Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1692. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1693. /// appropriate alignment. Cast it to the default address space if
  1694. /// \p CastToDefaultAddrSpace is true.
  1695. Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
  1696. bool CastToDefaultAddrSpace = true);
  1697. Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
  1698. bool CastToDefaultAddrSpace = true);
  1699. /// CreateAggTemp - Create a temporary memory object for the given
  1700. /// aggregate type.
  1701. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1702. return AggValueSlot::forAddr(CreateMemTemp(T, Name),
  1703. T.getQualifiers(),
  1704. AggValueSlot::IsNotDestructed,
  1705. AggValueSlot::DoesNotNeedGCBarriers,
  1706. AggValueSlot::IsNotAliased);
  1707. }
  1708. /// Emit a cast to void* in the appropriate address space.
  1709. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1710. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1711. /// expression and compare the result against zero, returning an Int1Ty value.
  1712. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1713. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1714. void EmitIgnoredExpr(const Expr *E);
  1715. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1716. /// any type. The result is returned as an RValue struct. If this is an
  1717. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1718. /// the result should be returned.
  1719. ///
  1720. /// \param ignoreResult True if the resulting value isn't used.
  1721. RValue EmitAnyExpr(const Expr *E,
  1722. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1723. bool ignoreResult = false);
  1724. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1725. // or the value of the expression, depending on how va_list is defined.
  1726. Address EmitVAListRef(const Expr *E);
  1727. /// Emit a "reference" to a __builtin_ms_va_list; this is
  1728. /// always the value of the expression, because a __builtin_ms_va_list is a
  1729. /// pointer to a char.
  1730. Address EmitMSVAListRef(const Expr *E);
  1731. /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
  1732. /// always be accessible even if no aggregate location is provided.
  1733. RValue EmitAnyExprToTemp(const Expr *E);
  1734. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1735. /// arbitrary expression into the given memory location.
  1736. void EmitAnyExprToMem(const Expr *E, Address Location,
  1737. Qualifiers Quals, bool IsInitializer);
  1738. void EmitAnyExprToExn(const Expr *E, Address Addr);
  1739. /// EmitExprAsInit - Emits the code necessary to initialize a
  1740. /// location in memory with the given initializer.
  1741. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1742. bool capturedByInit);
  1743. /// hasVolatileMember - returns true if aggregate type has a volatile
  1744. /// member.
  1745. bool hasVolatileMember(QualType T) {
  1746. if (const RecordType *RT = T->getAs<RecordType>()) {
  1747. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1748. return RD->hasVolatileMember();
  1749. }
  1750. return false;
  1751. }
  1752. /// EmitAggregateCopy - Emit an aggregate assignment.
  1753. ///
  1754. /// The difference to EmitAggregateCopy is that tail padding is not copied.
  1755. /// This is required for correctness when assigning non-POD structures in C++.
  1756. void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
  1757. QualType EltTy) {
  1758. bool IsVolatile = hasVolatileMember(EltTy);
  1759. EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
  1760. }
  1761. void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
  1762. QualType DestTy, QualType SrcTy) {
  1763. EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
  1764. /*IsAssignment=*/false);
  1765. }
  1766. /// EmitAggregateCopy - Emit an aggregate copy.
  1767. ///
  1768. /// \param isVolatile - True iff either the source or the destination is
  1769. /// volatile.
  1770. /// \param isAssignment - If false, allow padding to be copied. This often
  1771. /// yields more efficient.
  1772. void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
  1773. QualType EltTy, bool isVolatile=false,
  1774. bool isAssignment = false);
  1775. /// GetAddrOfLocalVar - Return the address of a local variable.
  1776. Address GetAddrOfLocalVar(const VarDecl *VD) {
  1777. auto it = LocalDeclMap.find(VD);
  1778. assert(it != LocalDeclMap.end() &&
  1779. "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1780. return it->second;
  1781. }
  1782. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1783. /// must be mapped to an l-value), return its mapping.
  1784. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1785. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1786. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1787. it = OpaqueLValues.find(e);
  1788. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1789. return it->second;
  1790. }
  1791. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1792. /// must be mapped to an r-value), return its mapping.
  1793. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1794. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1795. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1796. it = OpaqueRValues.find(e);
  1797. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1798. return it->second;
  1799. }
  1800. /// Get the index of the current ArrayInitLoopExpr, if any.
  1801. llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
  1802. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1803. /// the input field number being accessed.
  1804. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1805. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1806. llvm::BasicBlock *GetIndirectGotoBlock();
  1807. /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
  1808. static bool IsWrappedCXXThis(const Expr *E);
  1809. /// EmitNullInitialization - Generate code to set a value of the given type to
  1810. /// null, If the type contains data member pointers, they will be initialized
  1811. /// to -1 in accordance with the Itanium C++ ABI.
  1812. void EmitNullInitialization(Address DestPtr, QualType Ty);
  1813. /// Emits a call to an LLVM variable-argument intrinsic, either
  1814. /// \c llvm.va_start or \c llvm.va_end.
  1815. /// \param ArgValue A reference to the \c va_list as emitted by either
  1816. /// \c EmitVAListRef or \c EmitMSVAListRef.
  1817. /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
  1818. /// calls \c llvm.va_end.
  1819. llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
  1820. /// Generate code to get an argument from the passed in pointer
  1821. /// and update it accordingly.
  1822. /// \param VE The \c VAArgExpr for which to generate code.
  1823. /// \param VAListAddr Receives a reference to the \c va_list as emitted by
  1824. /// either \c EmitVAListRef or \c EmitMSVAListRef.
  1825. /// \returns A pointer to the argument.
  1826. // FIXME: We should be able to get rid of this method and use the va_arg
  1827. // instruction in LLVM instead once it works well enough.
  1828. Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
  1829. /// emitArrayLength - Compute the length of an array, even if it's a
  1830. /// VLA, and drill down to the base element type.
  1831. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1832. QualType &baseType,
  1833. Address &addr);
  1834. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1835. /// the given variably-modified type and store them in the VLASizeMap.
  1836. ///
  1837. /// This function can be called with a null (unreachable) insert point.
  1838. void EmitVariablyModifiedType(QualType Ty);
  1839. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1840. /// in non-variably-sized elements, of a variable length array type,
  1841. /// plus that largest non-variably-sized element type. Assumes that
  1842. /// the type has already been emitted with EmitVariablyModifiedType.
  1843. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1844. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1845. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1846. /// generating code for an C++ member function.
  1847. llvm::Value *LoadCXXThis() {
  1848. assert(CXXThisValue && "no 'this' value for this function");
  1849. return CXXThisValue;
  1850. }
  1851. Address LoadCXXThisAddress();
  1852. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1853. /// virtual bases.
  1854. // FIXME: Every place that calls LoadCXXVTT is something
  1855. // that needs to be abstracted properly.
  1856. llvm::Value *LoadCXXVTT() {
  1857. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  1858. return CXXStructorImplicitParamValue;
  1859. }
  1860. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1861. /// complete class to the given direct base.
  1862. Address
  1863. GetAddressOfDirectBaseInCompleteClass(Address Value,
  1864. const CXXRecordDecl *Derived,
  1865. const CXXRecordDecl *Base,
  1866. bool BaseIsVirtual);
  1867. static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
  1868. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1869. /// load of 'this' and returns address of the base class.
  1870. Address GetAddressOfBaseClass(Address Value,
  1871. const CXXRecordDecl *Derived,
  1872. CastExpr::path_const_iterator PathBegin,
  1873. CastExpr::path_const_iterator PathEnd,
  1874. bool NullCheckValue, SourceLocation Loc);
  1875. Address GetAddressOfDerivedClass(Address Value,
  1876. const CXXRecordDecl *Derived,
  1877. CastExpr::path_const_iterator PathBegin,
  1878. CastExpr::path_const_iterator PathEnd,
  1879. bool NullCheckValue);
  1880. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  1881. /// base constructor/destructor with virtual bases.
  1882. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  1883. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  1884. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  1885. bool Delegating);
  1886. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1887. CXXCtorType CtorType,
  1888. const FunctionArgList &Args,
  1889. SourceLocation Loc);
  1890. // It's important not to confuse this and the previous function. Delegating
  1891. // constructors are the C++0x feature. The constructor delegate optimization
  1892. // is used to reduce duplication in the base and complete consturctors where
  1893. // they are substantially the same.
  1894. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1895. const FunctionArgList &Args);
  1896. /// Emit a call to an inheriting constructor (that is, one that invokes a
  1897. /// constructor inherited from a base class) by inlining its definition. This
  1898. /// is necessary if the ABI does not support forwarding the arguments to the
  1899. /// base class constructor (because they're variadic or similar).
  1900. void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1901. CXXCtorType CtorType,
  1902. bool ForVirtualBase,
  1903. bool Delegating,
  1904. CallArgList &Args);
  1905. /// Emit a call to a constructor inherited from a base class, passing the
  1906. /// current constructor's arguments along unmodified (without even making
  1907. /// a copy).
  1908. void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
  1909. bool ForVirtualBase, Address This,
  1910. bool InheritedFromVBase,
  1911. const CXXInheritedCtorInitExpr *E);
  1912. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1913. bool ForVirtualBase, bool Delegating,
  1914. Address This, const CXXConstructExpr *E);
  1915. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1916. bool ForVirtualBase, bool Delegating,
  1917. Address This, CallArgList &Args);
  1918. /// Emit assumption load for all bases. Requires to be be called only on
  1919. /// most-derived class and not under construction of the object.
  1920. void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
  1921. /// Emit assumption that vptr load == global vtable.
  1922. void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
  1923. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1924. Address This, Address Src,
  1925. const CXXConstructExpr *E);
  1926. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1927. const ArrayType *ArrayTy,
  1928. Address ArrayPtr,
  1929. const CXXConstructExpr *E,
  1930. bool ZeroInitialization = false);
  1931. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1932. llvm::Value *NumElements,
  1933. Address ArrayPtr,
  1934. const CXXConstructExpr *E,
  1935. bool ZeroInitialization = false);
  1936. static Destroyer destroyCXXObject;
  1937. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1938. bool ForVirtualBase, bool Delegating,
  1939. Address This);
  1940. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1941. llvm::Type *ElementTy, Address NewPtr,
  1942. llvm::Value *NumElements,
  1943. llvm::Value *AllocSizeWithoutCookie);
  1944. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1945. Address Ptr);
  1946. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  1947. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  1948. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1949. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1950. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1951. QualType DeleteTy, llvm::Value *NumElements = nullptr,
  1952. CharUnits CookieSize = CharUnits());
  1953. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  1954. const Expr *Arg, bool IsDelete);
  1955. llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1956. llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
  1957. Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  1958. /// \brief Situations in which we might emit a check for the suitability of a
  1959. /// pointer or glvalue.
  1960. enum TypeCheckKind {
  1961. /// Checking the operand of a load. Must be suitably sized and aligned.
  1962. TCK_Load,
  1963. /// Checking the destination of a store. Must be suitably sized and aligned.
  1964. TCK_Store,
  1965. /// Checking the bound value in a reference binding. Must be suitably sized
  1966. /// and aligned, but is not required to refer to an object (until the
  1967. /// reference is used), per core issue 453.
  1968. TCK_ReferenceBinding,
  1969. /// Checking the object expression in a non-static data member access. Must
  1970. /// be an object within its lifetime.
  1971. TCK_MemberAccess,
  1972. /// Checking the 'this' pointer for a call to a non-static member function.
  1973. /// Must be an object within its lifetime.
  1974. TCK_MemberCall,
  1975. /// Checking the 'this' pointer for a constructor call.
  1976. TCK_ConstructorCall,
  1977. /// Checking the operand of a static_cast to a derived pointer type. Must be
  1978. /// null or an object within its lifetime.
  1979. TCK_DowncastPointer,
  1980. /// Checking the operand of a static_cast to a derived reference type. Must
  1981. /// be an object within its lifetime.
  1982. TCK_DowncastReference,
  1983. /// Checking the operand of a cast to a base object. Must be suitably sized
  1984. /// and aligned.
  1985. TCK_Upcast,
  1986. /// Checking the operand of a cast to a virtual base object. Must be an
  1987. /// object within its lifetime.
  1988. TCK_UpcastToVirtualBase,
  1989. /// Checking the value assigned to a _Nonnull pointer. Must not be null.
  1990. TCK_NonnullAssign
  1991. };
  1992. /// Determine whether the pointer type check \p TCK permits null pointers.
  1993. static bool isNullPointerAllowed(TypeCheckKind TCK);
  1994. /// Determine whether the pointer type check \p TCK requires a vptr check.
  1995. static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
  1996. /// \brief Whether any type-checking sanitizers are enabled. If \c false,
  1997. /// calls to EmitTypeCheck can be skipped.
  1998. bool sanitizePerformTypeCheck() const;
  1999. /// \brief Emit a check that \p V is the address of storage of the
  2000. /// appropriate size and alignment for an object of type \p Type.
  2001. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  2002. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  2003. SanitizerSet SkippedChecks = SanitizerSet());
  2004. /// \brief Emit a check that \p Base points into an array object, which
  2005. /// we can access at index \p Index. \p Accessed should be \c false if we
  2006. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  2007. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  2008. QualType IndexType, bool Accessed);
  2009. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  2010. bool isInc, bool isPre);
  2011. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  2012. bool isInc, bool isPre);
  2013. void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
  2014. llvm::Value *OffsetValue = nullptr) {
  2015. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  2016. OffsetValue);
  2017. }
  2018. /// Converts Location to a DebugLoc, if debug information is enabled.
  2019. llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
  2020. //===--------------------------------------------------------------------===//
  2021. // Declaration Emission
  2022. //===--------------------------------------------------------------------===//
  2023. /// EmitDecl - Emit a declaration.
  2024. ///
  2025. /// This function can be called with a null (unreachable) insert point.
  2026. void EmitDecl(const Decl &D);
  2027. /// EmitVarDecl - Emit a local variable declaration.
  2028. ///
  2029. /// This function can be called with a null (unreachable) insert point.
  2030. void EmitVarDecl(const VarDecl &D);
  2031. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  2032. bool capturedByInit);
  2033. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  2034. llvm::Value *Address);
  2035. /// \brief Determine whether the given initializer is trivial in the sense
  2036. /// that it requires no code to be generated.
  2037. bool isTrivialInitializer(const Expr *Init);
  2038. /// EmitAutoVarDecl - Emit an auto variable declaration.
  2039. ///
  2040. /// This function can be called with a null (unreachable) insert point.
  2041. void EmitAutoVarDecl(const VarDecl &D);
  2042. class AutoVarEmission {
  2043. friend class CodeGenFunction;
  2044. const VarDecl *Variable;
  2045. /// The address of the alloca. Invalid if the variable was emitted
  2046. /// as a global constant.
  2047. Address Addr;
  2048. llvm::Value *NRVOFlag;
  2049. /// True if the variable is a __block variable.
  2050. bool IsByRef;
  2051. /// True if the variable is of aggregate type and has a constant
  2052. /// initializer.
  2053. bool IsConstantAggregate;
  2054. /// Non-null if we should use lifetime annotations.
  2055. llvm::Value *SizeForLifetimeMarkers;
  2056. struct Invalid {};
  2057. AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
  2058. AutoVarEmission(const VarDecl &variable)
  2059. : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
  2060. IsByRef(false), IsConstantAggregate(false),
  2061. SizeForLifetimeMarkers(nullptr) {}
  2062. bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
  2063. public:
  2064. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  2065. bool useLifetimeMarkers() const {
  2066. return SizeForLifetimeMarkers != nullptr;
  2067. }
  2068. llvm::Value *getSizeForLifetimeMarkers() const {
  2069. assert(useLifetimeMarkers());
  2070. return SizeForLifetimeMarkers;
  2071. }
  2072. /// Returns the raw, allocated address, which is not necessarily
  2073. /// the address of the object itself.
  2074. Address getAllocatedAddress() const {
  2075. return Addr;
  2076. }
  2077. /// Returns the address of the object within this declaration.
  2078. /// Note that this does not chase the forwarding pointer for
  2079. /// __block decls.
  2080. Address getObjectAddress(CodeGenFunction &CGF) const {
  2081. if (!IsByRef) return Addr;
  2082. return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
  2083. }
  2084. };
  2085. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  2086. void EmitAutoVarInit(const AutoVarEmission &emission);
  2087. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  2088. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  2089. QualType::DestructionKind dtorKind);
  2090. void EmitStaticVarDecl(const VarDecl &D,
  2091. llvm::GlobalValue::LinkageTypes Linkage);
  2092. class ParamValue {
  2093. llvm::Value *Value;
  2094. unsigned Alignment;
  2095. ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
  2096. public:
  2097. static ParamValue forDirect(llvm::Value *value) {
  2098. return ParamValue(value, 0);
  2099. }
  2100. static ParamValue forIndirect(Address addr) {
  2101. assert(!addr.getAlignment().isZero());
  2102. return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
  2103. }
  2104. bool isIndirect() const { return Alignment != 0; }
  2105. llvm::Value *getAnyValue() const { return Value; }
  2106. llvm::Value *getDirectValue() const {
  2107. assert(!isIndirect());
  2108. return Value;
  2109. }
  2110. Address getIndirectAddress() const {
  2111. assert(isIndirect());
  2112. return Address(Value, CharUnits::fromQuantity(Alignment));
  2113. }
  2114. };
  2115. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  2116. void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
  2117. /// protectFromPeepholes - Protect a value that we're intending to
  2118. /// store to the side, but which will probably be used later, from
  2119. /// aggressive peepholing optimizations that might delete it.
  2120. ///
  2121. /// Pass the result to unprotectFromPeepholes to declare that
  2122. /// protection is no longer required.
  2123. ///
  2124. /// There's no particular reason why this shouldn't apply to
  2125. /// l-values, it's just that no existing peepholes work on pointers.
  2126. PeepholeProtection protectFromPeepholes(RValue rvalue);
  2127. void unprotectFromPeepholes(PeepholeProtection protection);
  2128. void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
  2129. llvm::Value *OffsetValue = nullptr) {
  2130. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  2131. OffsetValue);
  2132. }
  2133. //===--------------------------------------------------------------------===//
  2134. // Statement Emission
  2135. //===--------------------------------------------------------------------===//
  2136. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  2137. void EmitStopPoint(const Stmt *S);
  2138. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  2139. /// this function even if there is no current insertion point.
  2140. ///
  2141. /// This function may clear the current insertion point; callers should use
  2142. /// EnsureInsertPoint if they wish to subsequently generate code without first
  2143. /// calling EmitBlock, EmitBranch, or EmitStmt.
  2144. void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
  2145. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  2146. /// necessarily require an insertion point or debug information; typically
  2147. /// because the statement amounts to a jump or a container of other
  2148. /// statements.
  2149. ///
  2150. /// \return True if the statement was handled.
  2151. bool EmitSimpleStmt(const Stmt *S);
  2152. Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  2153. AggValueSlot AVS = AggValueSlot::ignored());
  2154. Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  2155. bool GetLast = false,
  2156. AggValueSlot AVS =
  2157. AggValueSlot::ignored());
  2158. /// EmitLabel - Emit the block for the given label. It is legal to call this
  2159. /// function even if there is no current insertion point.
  2160. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  2161. void EmitLabelStmt(const LabelStmt &S);
  2162. void EmitAttributedStmt(const AttributedStmt &S);
  2163. void EmitGotoStmt(const GotoStmt &S);
  2164. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  2165. void EmitIfStmt(const IfStmt &S);
  2166. void EmitWhileStmt(const WhileStmt &S,
  2167. ArrayRef<const Attr *> Attrs = None);
  2168. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  2169. void EmitForStmt(const ForStmt &S,
  2170. ArrayRef<const Attr *> Attrs = None);
  2171. void EmitReturnStmt(const ReturnStmt &S);
  2172. void EmitDeclStmt(const DeclStmt &S);
  2173. void EmitBreakStmt(const BreakStmt &S);
  2174. void EmitContinueStmt(const ContinueStmt &S);
  2175. void EmitSwitchStmt(const SwitchStmt &S);
  2176. void EmitDefaultStmt(const DefaultStmt &S);
  2177. void EmitCaseStmt(const CaseStmt &S);
  2178. void EmitCaseStmtRange(const CaseStmt &S);
  2179. void EmitAsmStmt(const AsmStmt &S);
  2180. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  2181. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  2182. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  2183. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  2184. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  2185. void EmitCoroutineBody(const CoroutineBodyStmt &S);
  2186. void EmitCoreturnStmt(const CoreturnStmt &S);
  2187. RValue EmitCoawaitExpr(const CoawaitExpr &E,
  2188. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2189. bool ignoreResult = false);
  2190. LValue EmitCoawaitLValue(const CoawaitExpr *E);
  2191. RValue EmitCoyieldExpr(const CoyieldExpr &E,
  2192. AggValueSlot aggSlot = AggValueSlot::ignored(),
  2193. bool ignoreResult = false);
  2194. LValue EmitCoyieldLValue(const CoyieldExpr *E);
  2195. RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
  2196. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2197. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  2198. void EmitCXXTryStmt(const CXXTryStmt &S);
  2199. void EmitSEHTryStmt(const SEHTryStmt &S);
  2200. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  2201. void EnterSEHTryStmt(const SEHTryStmt &S);
  2202. void ExitSEHTryStmt(const SEHTryStmt &S);
  2203. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  2204. const Stmt *OutlinedStmt);
  2205. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  2206. const SEHExceptStmt &Except);
  2207. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  2208. const SEHFinallyStmt &Finally);
  2209. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  2210. llvm::Value *ParentFP,
  2211. llvm::Value *EntryEBP);
  2212. llvm::Value *EmitSEHExceptionCode();
  2213. llvm::Value *EmitSEHExceptionInfo();
  2214. llvm::Value *EmitSEHAbnormalTermination();
  2215. /// Scan the outlined statement for captures from the parent function. For
  2216. /// each capture, mark the capture as escaped and emit a call to
  2217. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  2218. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  2219. bool IsFilter);
  2220. /// Recovers the address of a local in a parent function. ParentVar is the
  2221. /// address of the variable used in the immediate parent function. It can
  2222. /// either be an alloca or a call to llvm.localrecover if there are nested
  2223. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  2224. /// frame.
  2225. Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  2226. Address ParentVar,
  2227. llvm::Value *ParentFP);
  2228. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  2229. ArrayRef<const Attr *> Attrs = None);
  2230. /// Controls insertion of cancellation exit blocks in worksharing constructs.
  2231. class OMPCancelStackRAII {
  2232. CodeGenFunction &CGF;
  2233. public:
  2234. OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
  2235. bool HasCancel)
  2236. : CGF(CGF) {
  2237. CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
  2238. }
  2239. ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
  2240. };
  2241. /// Returns calculated size of the specified type.
  2242. llvm::Value *getTypeSize(QualType Ty);
  2243. LValue InitCapturedStruct(const CapturedStmt &S);
  2244. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  2245. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  2246. Address GenerateCapturedStmtArgument(const CapturedStmt &S);
  2247. llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
  2248. void GenerateOpenMPCapturedVars(const CapturedStmt &S,
  2249. SmallVectorImpl<llvm::Value *> &CapturedVars);
  2250. void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
  2251. SourceLocation Loc);
  2252. /// \brief Perform element by element copying of arrays with type \a
  2253. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  2254. /// generated by \a CopyGen.
  2255. ///
  2256. /// \param DestAddr Address of the destination array.
  2257. /// \param SrcAddr Address of the source array.
  2258. /// \param OriginalType Type of destination and source arrays.
  2259. /// \param CopyGen Copying procedure that copies value of single array element
  2260. /// to another single array element.
  2261. void EmitOMPAggregateAssign(
  2262. Address DestAddr, Address SrcAddr, QualType OriginalType,
  2263. const llvm::function_ref<void(Address, Address)> &CopyGen);
  2264. /// \brief Emit proper copying of data from one variable to another.
  2265. ///
  2266. /// \param OriginalType Original type of the copied variables.
  2267. /// \param DestAddr Destination address.
  2268. /// \param SrcAddr Source address.
  2269. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  2270. /// type of the base array element).
  2271. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  2272. /// the base array element).
  2273. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  2274. /// DestVD.
  2275. void EmitOMPCopy(QualType OriginalType,
  2276. Address DestAddr, Address SrcAddr,
  2277. const VarDecl *DestVD, const VarDecl *SrcVD,
  2278. const Expr *Copy);
  2279. /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  2280. /// \a X = \a E \a BO \a E.
  2281. ///
  2282. /// \param X Value to be updated.
  2283. /// \param E Update value.
  2284. /// \param BO Binary operation for update operation.
  2285. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  2286. /// expression, false otherwise.
  2287. /// \param AO Atomic ordering of the generated atomic instructions.
  2288. /// \param CommonGen Code generator for complex expressions that cannot be
  2289. /// expressed through atomicrmw instruction.
  2290. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  2291. /// generated, <false, RValue::get(nullptr)> otherwise.
  2292. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  2293. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  2294. llvm::AtomicOrdering AO, SourceLocation Loc,
  2295. const llvm::function_ref<RValue(RValue)> &CommonGen);
  2296. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  2297. OMPPrivateScope &PrivateScope);
  2298. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  2299. OMPPrivateScope &PrivateScope);
  2300. void EmitOMPUseDevicePtrClause(
  2301. const OMPClause &C, OMPPrivateScope &PrivateScope,
  2302. const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
  2303. /// \brief Emit code for copyin clause in \a D directive. The next code is
  2304. /// generated at the start of outlined functions for directives:
  2305. /// \code
  2306. /// threadprivate_var1 = master_threadprivate_var1;
  2307. /// operator=(threadprivate_var2, master_threadprivate_var2);
  2308. /// ...
  2309. /// __kmpc_barrier(&loc, global_tid);
  2310. /// \endcode
  2311. ///
  2312. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  2313. /// \returns true if at least one copyin variable is found, false otherwise.
  2314. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  2315. /// \brief Emit initial code for lastprivate variables. If some variable is
  2316. /// not also firstprivate, then the default initialization is used. Otherwise
  2317. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  2318. /// method.
  2319. ///
  2320. /// \param D Directive that may have 'lastprivate' directives.
  2321. /// \param PrivateScope Private scope for capturing lastprivate variables for
  2322. /// proper codegen in internal captured statement.
  2323. ///
  2324. /// \returns true if there is at least one lastprivate variable, false
  2325. /// otherwise.
  2326. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  2327. OMPPrivateScope &PrivateScope);
  2328. /// \brief Emit final copying of lastprivate values to original variables at
  2329. /// the end of the worksharing or simd directive.
  2330. ///
  2331. /// \param D Directive that has at least one 'lastprivate' directives.
  2332. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  2333. /// it is the last iteration of the loop code in associated directive, or to
  2334. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  2335. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  2336. bool NoFinals,
  2337. llvm::Value *IsLastIterCond = nullptr);
  2338. /// Emit initial code for linear clauses.
  2339. void EmitOMPLinearClause(const OMPLoopDirective &D,
  2340. CodeGenFunction::OMPPrivateScope &PrivateScope);
  2341. /// Emit final code for linear clauses.
  2342. /// \param CondGen Optional conditional code for final part of codegen for
  2343. /// linear clause.
  2344. void EmitOMPLinearClauseFinal(
  2345. const OMPLoopDirective &D,
  2346. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
  2347. /// \brief Emit initial code for reduction variables. Creates reduction copies
  2348. /// and initializes them with the values according to OpenMP standard.
  2349. ///
  2350. /// \param D Directive (possibly) with the 'reduction' clause.
  2351. /// \param PrivateScope Private scope for capturing reduction variables for
  2352. /// proper codegen in internal captured statement.
  2353. ///
  2354. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  2355. OMPPrivateScope &PrivateScope);
  2356. /// \brief Emit final update of reduction values to original variables at
  2357. /// the end of the directive.
  2358. ///
  2359. /// \param D Directive that has at least one 'reduction' directives.
  2360. /// \param ReductionKind The kind of reduction to perform.
  2361. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
  2362. const OpenMPDirectiveKind ReductionKind);
  2363. /// \brief Emit initial code for linear variables. Creates private copies
  2364. /// and initializes them with the values according to OpenMP standard.
  2365. ///
  2366. /// \param D Directive (possibly) with the 'linear' clause.
  2367. /// \return true if at least one linear variable is found that should be
  2368. /// initialized with the value of the original variable, false otherwise.
  2369. bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  2370. typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
  2371. llvm::Value * /*OutlinedFn*/,
  2372. const OMPTaskDataTy & /*Data*/)>
  2373. TaskGenTy;
  2374. void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
  2375. const RegionCodeGenTy &BodyGen,
  2376. const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
  2377. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  2378. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  2379. void EmitOMPForDirective(const OMPForDirective &S);
  2380. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  2381. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  2382. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  2383. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  2384. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  2385. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  2386. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  2387. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  2388. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  2389. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  2390. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  2391. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  2392. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  2393. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  2394. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  2395. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  2396. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  2397. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  2398. void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
  2399. void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
  2400. void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
  2401. void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
  2402. void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
  2403. void
  2404. EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
  2405. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  2406. void
  2407. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  2408. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  2409. void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
  2410. void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
  2411. void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
  2412. void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
  2413. void EmitOMPDistributeParallelForDirective(
  2414. const OMPDistributeParallelForDirective &S);
  2415. void EmitOMPDistributeParallelForSimdDirective(
  2416. const OMPDistributeParallelForSimdDirective &S);
  2417. void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
  2418. void EmitOMPTargetParallelForSimdDirective(
  2419. const OMPTargetParallelForSimdDirective &S);
  2420. void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
  2421. void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
  2422. void
  2423. EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
  2424. void EmitOMPTeamsDistributeParallelForSimdDirective(
  2425. const OMPTeamsDistributeParallelForSimdDirective &S);
  2426. void EmitOMPTeamsDistributeParallelForDirective(
  2427. const OMPTeamsDistributeParallelForDirective &S);
  2428. void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
  2429. void EmitOMPTargetTeamsDistributeDirective(
  2430. const OMPTargetTeamsDistributeDirective &S);
  2431. void EmitOMPTargetTeamsDistributeParallelForDirective(
  2432. const OMPTargetTeamsDistributeParallelForDirective &S);
  2433. void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
  2434. const OMPTargetTeamsDistributeParallelForSimdDirective &S);
  2435. void EmitOMPTargetTeamsDistributeSimdDirective(
  2436. const OMPTargetTeamsDistributeSimdDirective &S);
  2437. /// Emit device code for the target directive.
  2438. static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
  2439. StringRef ParentName,
  2440. const OMPTargetDirective &S);
  2441. static void
  2442. EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  2443. const OMPTargetParallelDirective &S);
  2444. /// Emit device code for the target parallel for directive.
  2445. static void EmitOMPTargetParallelForDeviceFunction(
  2446. CodeGenModule &CGM, StringRef ParentName,
  2447. const OMPTargetParallelForDirective &S);
  2448. /// Emit device code for the target parallel for simd directive.
  2449. static void EmitOMPTargetParallelForSimdDeviceFunction(
  2450. CodeGenModule &CGM, StringRef ParentName,
  2451. const OMPTargetParallelForSimdDirective &S);
  2452. /// Emit device code for the target teams directive.
  2453. static void
  2454. EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
  2455. const OMPTargetTeamsDirective &S);
  2456. /// Emit device code for the target teams distribute directive.
  2457. static void EmitOMPTargetTeamsDistributeDeviceFunction(
  2458. CodeGenModule &CGM, StringRef ParentName,
  2459. const OMPTargetTeamsDistributeDirective &S);
  2460. /// Emit device code for the target teams distribute simd directive.
  2461. static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
  2462. CodeGenModule &CGM, StringRef ParentName,
  2463. const OMPTargetTeamsDistributeSimdDirective &S);
  2464. /// Emit device code for the target simd directive.
  2465. static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
  2466. StringRef ParentName,
  2467. const OMPTargetSimdDirective &S);
  2468. /// \brief Emit inner loop of the worksharing/simd construct.
  2469. ///
  2470. /// \param S Directive, for which the inner loop must be emitted.
  2471. /// \param RequiresCleanup true, if directive has some associated private
  2472. /// variables.
  2473. /// \param LoopCond Bollean condition for loop continuation.
  2474. /// \param IncExpr Increment expression for loop control variable.
  2475. /// \param BodyGen Generator for the inner body of the inner loop.
  2476. /// \param PostIncGen Genrator for post-increment code (required for ordered
  2477. /// loop directvies).
  2478. void EmitOMPInnerLoop(
  2479. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  2480. const Expr *IncExpr,
  2481. const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
  2482. const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
  2483. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  2484. /// Emit initial code for loop counters of loop-based directives.
  2485. void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
  2486. OMPPrivateScope &LoopScope);
  2487. /// Helper for the OpenMP loop directives.
  2488. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  2489. /// \brief Emit code for the worksharing loop-based directive.
  2490. /// \return true, if this construct has any lastprivate clause, false -
  2491. /// otherwise.
  2492. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
  2493. const CodeGenLoopBoundsTy &CodeGenLoopBounds,
  2494. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  2495. /// Emit code for the distribute loop-based directive.
  2496. void EmitOMPDistributeLoop(const OMPLoopDirective &S,
  2497. const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
  2498. /// Helpers for the OpenMP loop directives.
  2499. void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
  2500. void EmitOMPSimdFinal(
  2501. const OMPLoopDirective &D,
  2502. const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
  2503. /// Emits the lvalue for the expression with possibly captured variable.
  2504. LValue EmitOMPSharedLValue(const Expr *E);
  2505. private:
  2506. /// Helpers for blocks. Returns invoke function by \p InvokeF if it is not
  2507. /// nullptr. It should be called without \p InvokeF if the caller does not
  2508. /// need invoke function to be returned.
  2509. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info,
  2510. llvm::Function **InvokeF = nullptr);
  2511. /// struct with the values to be passed to the OpenMP loop-related functions
  2512. struct OMPLoopArguments {
  2513. /// loop lower bound
  2514. Address LB = Address::invalid();
  2515. /// loop upper bound
  2516. Address UB = Address::invalid();
  2517. /// loop stride
  2518. Address ST = Address::invalid();
  2519. /// isLastIteration argument for runtime functions
  2520. Address IL = Address::invalid();
  2521. /// Chunk value generated by sema
  2522. llvm::Value *Chunk = nullptr;
  2523. /// EnsureUpperBound
  2524. Expr *EUB = nullptr;
  2525. /// IncrementExpression
  2526. Expr *IncExpr = nullptr;
  2527. /// Loop initialization
  2528. Expr *Init = nullptr;
  2529. /// Loop exit condition
  2530. Expr *Cond = nullptr;
  2531. /// Update of LB after a whole chunk has been executed
  2532. Expr *NextLB = nullptr;
  2533. /// Update of UB after a whole chunk has been executed
  2534. Expr *NextUB = nullptr;
  2535. OMPLoopArguments() = default;
  2536. OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
  2537. llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
  2538. Expr *IncExpr = nullptr, Expr *Init = nullptr,
  2539. Expr *Cond = nullptr, Expr *NextLB = nullptr,
  2540. Expr *NextUB = nullptr)
  2541. : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
  2542. IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
  2543. NextUB(NextUB) {}
  2544. };
  2545. void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
  2546. const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
  2547. const OMPLoopArguments &LoopArgs,
  2548. const CodeGenLoopTy &CodeGenLoop,
  2549. const CodeGenOrderedTy &CodeGenOrdered);
  2550. void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
  2551. bool IsMonotonic, const OMPLoopDirective &S,
  2552. OMPPrivateScope &LoopScope, bool Ordered,
  2553. const OMPLoopArguments &LoopArgs,
  2554. const CodeGenDispatchBoundsTy &CGDispatchBounds);
  2555. void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
  2556. const OMPLoopDirective &S,
  2557. OMPPrivateScope &LoopScope,
  2558. const OMPLoopArguments &LoopArgs,
  2559. const CodeGenLoopTy &CodeGenLoopContent);
  2560. /// \brief Emit code for sections directive.
  2561. void EmitSections(const OMPExecutableDirective &S);
  2562. public:
  2563. //===--------------------------------------------------------------------===//
  2564. // LValue Expression Emission
  2565. //===--------------------------------------------------------------------===//
  2566. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  2567. RValue GetUndefRValue(QualType Ty);
  2568. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  2569. /// and issue an ErrorUnsupported style diagnostic (using the
  2570. /// provided Name).
  2571. RValue EmitUnsupportedRValue(const Expr *E,
  2572. const char *Name);
  2573. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  2574. /// an ErrorUnsupported style diagnostic (using the provided Name).
  2575. LValue EmitUnsupportedLValue(const Expr *E,
  2576. const char *Name);
  2577. /// EmitLValue - Emit code to compute a designator that specifies the location
  2578. /// of the expression.
  2579. ///
  2580. /// This can return one of two things: a simple address or a bitfield
  2581. /// reference. In either case, the LLVM Value* in the LValue structure is
  2582. /// guaranteed to be an LLVM pointer type.
  2583. ///
  2584. /// If this returns a bitfield reference, nothing about the pointee type of
  2585. /// the LLVM value is known: For example, it may not be a pointer to an
  2586. /// integer.
  2587. ///
  2588. /// If this returns a normal address, and if the lvalue's C type is fixed
  2589. /// size, this method guarantees that the returned pointer type will point to
  2590. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  2591. /// variable length type, this is not possible.
  2592. ///
  2593. LValue EmitLValue(const Expr *E);
  2594. /// \brief Same as EmitLValue but additionally we generate checking code to
  2595. /// guard against undefined behavior. This is only suitable when we know
  2596. /// that the address will be used to access the object.
  2597. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  2598. RValue convertTempToRValue(Address addr, QualType type,
  2599. SourceLocation Loc);
  2600. void EmitAtomicInit(Expr *E, LValue lvalue);
  2601. bool LValueIsSuitableForInlineAtomic(LValue Src);
  2602. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  2603. AggValueSlot Slot = AggValueSlot::ignored());
  2604. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  2605. llvm::AtomicOrdering AO, bool IsVolatile = false,
  2606. AggValueSlot slot = AggValueSlot::ignored());
  2607. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  2608. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  2609. bool IsVolatile, bool isInit);
  2610. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  2611. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  2612. llvm::AtomicOrdering Success =
  2613. llvm::AtomicOrdering::SequentiallyConsistent,
  2614. llvm::AtomicOrdering Failure =
  2615. llvm::AtomicOrdering::SequentiallyConsistent,
  2616. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  2617. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  2618. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  2619. bool IsVolatile);
  2620. /// EmitToMemory - Change a scalar value from its value
  2621. /// representation to its in-memory representation.
  2622. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  2623. /// EmitFromMemory - Change a scalar value from its memory
  2624. /// representation to its value representation.
  2625. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  2626. /// Check if the scalar \p Value is within the valid range for the given
  2627. /// type \p Ty.
  2628. ///
  2629. /// Returns true if a check is needed (even if the range is unknown).
  2630. bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  2631. SourceLocation Loc);
  2632. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2633. /// care to appropriately convert from the memory representation to
  2634. /// the LLVM value representation.
  2635. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2636. SourceLocation Loc,
  2637. AlignmentSource Source = AlignmentSource::Type,
  2638. bool isNontemporal = false) {
  2639. return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
  2640. CGM.getTBAAAccessInfo(Ty), isNontemporal);
  2641. }
  2642. llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
  2643. SourceLocation Loc, LValueBaseInfo BaseInfo,
  2644. TBAAAccessInfo TBAAInfo,
  2645. bool isNontemporal = false);
  2646. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  2647. /// care to appropriately convert from the memory representation to
  2648. /// the LLVM value representation. The l-value must be a simple
  2649. /// l-value.
  2650. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  2651. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2652. /// care to appropriately convert from the memory representation to
  2653. /// the LLVM value representation.
  2654. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2655. bool Volatile, QualType Ty,
  2656. AlignmentSource Source = AlignmentSource::Type,
  2657. bool isInit = false, bool isNontemporal = false) {
  2658. EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
  2659. CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
  2660. }
  2661. void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  2662. bool Volatile, QualType Ty,
  2663. LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
  2664. bool isInit = false, bool isNontemporal = false);
  2665. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2666. /// care to appropriately convert from the memory representation to
  2667. /// the LLVM value representation. The l-value must be a simple
  2668. /// l-value. The isInit flag indicates whether this is an initialization.
  2669. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  2670. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  2671. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  2672. /// this method emits the address of the lvalue, then loads the result as an
  2673. /// rvalue, returning the rvalue.
  2674. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  2675. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  2676. RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
  2677. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  2678. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  2679. /// lvalue, where both are guaranteed to the have the same type, and that type
  2680. /// is 'Ty'.
  2681. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  2682. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  2683. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  2684. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  2685. /// as EmitStoreThroughLValue.
  2686. ///
  2687. /// \param Result [out] - If non-null, this will be set to a Value* for the
  2688. /// bit-field contents after the store, appropriate for use as the result of
  2689. /// an assignment to the bit-field.
  2690. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  2691. llvm::Value **Result=nullptr);
  2692. /// Emit an l-value for an assignment (simple or compound) of complex type.
  2693. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  2694. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2695. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  2696. llvm::Value *&Result);
  2697. // Note: only available for agg return types
  2698. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  2699. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2700. // Note: only available for agg return types
  2701. LValue EmitCallExprLValue(const CallExpr *E);
  2702. // Note: only available for agg return types
  2703. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  2704. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  2705. LValue EmitStringLiteralLValue(const StringLiteral *E);
  2706. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  2707. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  2708. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  2709. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2710. bool Accessed = false);
  2711. LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  2712. bool IsLowerBound = true);
  2713. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  2714. LValue EmitMemberExpr(const MemberExpr *E);
  2715. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  2716. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  2717. LValue EmitInitListLValue(const InitListExpr *E);
  2718. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  2719. LValue EmitCastLValue(const CastExpr *E);
  2720. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2721. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  2722. Address EmitExtVectorElementLValue(LValue V);
  2723. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  2724. Address EmitArrayToPointerDecay(const Expr *Array,
  2725. LValueBaseInfo *BaseInfo = nullptr,
  2726. TBAAAccessInfo *TBAAInfo = nullptr);
  2727. class ConstantEmission {
  2728. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  2729. ConstantEmission(llvm::Constant *C, bool isReference)
  2730. : ValueAndIsReference(C, isReference) {}
  2731. public:
  2732. ConstantEmission() {}
  2733. static ConstantEmission forReference(llvm::Constant *C) {
  2734. return ConstantEmission(C, true);
  2735. }
  2736. static ConstantEmission forValue(llvm::Constant *C) {
  2737. return ConstantEmission(C, false);
  2738. }
  2739. explicit operator bool() const {
  2740. return ValueAndIsReference.getOpaqueValue() != nullptr;
  2741. }
  2742. bool isReference() const { return ValueAndIsReference.getInt(); }
  2743. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  2744. assert(isReference());
  2745. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  2746. refExpr->getType());
  2747. }
  2748. llvm::Constant *getValue() const {
  2749. assert(!isReference());
  2750. return ValueAndIsReference.getPointer();
  2751. }
  2752. };
  2753. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  2754. ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
  2755. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  2756. AggValueSlot slot = AggValueSlot::ignored());
  2757. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  2758. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  2759. const ObjCIvarDecl *Ivar);
  2760. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  2761. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  2762. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  2763. /// if the Field is a reference, this will return the address of the reference
  2764. /// and not the address of the value stored in the reference.
  2765. LValue EmitLValueForFieldInitialization(LValue Base,
  2766. const FieldDecl* Field);
  2767. LValue EmitLValueForIvar(QualType ObjectTy,
  2768. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  2769. unsigned CVRQualifiers);
  2770. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  2771. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  2772. LValue EmitLambdaLValue(const LambdaExpr *E);
  2773. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  2774. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  2775. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  2776. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  2777. LValue EmitStmtExprLValue(const StmtExpr *E);
  2778. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  2779. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  2780. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
  2781. //===--------------------------------------------------------------------===//
  2782. // Scalar Expression Emission
  2783. //===--------------------------------------------------------------------===//
  2784. /// EmitCall - Generate a call of the given function, expecting the given
  2785. /// result type, and using the given argument list which specifies both the
  2786. /// LLVM arguments and the types they were derived from.
  2787. RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
  2788. ReturnValueSlot ReturnValue, const CallArgList &Args,
  2789. llvm::Instruction **callOrInvoke = nullptr);
  2790. RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
  2791. ReturnValueSlot ReturnValue,
  2792. llvm::Value *Chain = nullptr);
  2793. RValue EmitCallExpr(const CallExpr *E,
  2794. ReturnValueSlot ReturnValue = ReturnValueSlot());
  2795. RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  2796. CGCallee EmitCallee(const Expr *E);
  2797. void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
  2798. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2799. const Twine &name = "");
  2800. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2801. ArrayRef<llvm::Value*> args,
  2802. const Twine &name = "");
  2803. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2804. const Twine &name = "");
  2805. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2806. ArrayRef<llvm::Value*> args,
  2807. const Twine &name = "");
  2808. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2809. ArrayRef<llvm::Value *> Args,
  2810. const Twine &Name = "");
  2811. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2812. ArrayRef<llvm::Value*> args,
  2813. const Twine &name = "");
  2814. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2815. const Twine &name = "");
  2816. void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2817. ArrayRef<llvm::Value*> args);
  2818. CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  2819. NestedNameSpecifier *Qual,
  2820. llvm::Type *Ty);
  2821. CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  2822. CXXDtorType Type,
  2823. const CXXRecordDecl *RD);
  2824. RValue
  2825. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
  2826. const CGCallee &Callee,
  2827. ReturnValueSlot ReturnValue, llvm::Value *This,
  2828. llvm::Value *ImplicitParam,
  2829. QualType ImplicitParamTy, const CallExpr *E,
  2830. CallArgList *RtlArgs);
  2831. RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  2832. const CGCallee &Callee,
  2833. llvm::Value *This, llvm::Value *ImplicitParam,
  2834. QualType ImplicitParamTy, const CallExpr *E,
  2835. StructorType Type);
  2836. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  2837. ReturnValueSlot ReturnValue);
  2838. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  2839. const CXXMethodDecl *MD,
  2840. ReturnValueSlot ReturnValue,
  2841. bool HasQualifier,
  2842. NestedNameSpecifier *Qualifier,
  2843. bool IsArrow, const Expr *Base);
  2844. // Compute the object pointer.
  2845. Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  2846. llvm::Value *memberPtr,
  2847. const MemberPointerType *memberPtrType,
  2848. LValueBaseInfo *BaseInfo = nullptr,
  2849. TBAAAccessInfo *TBAAInfo = nullptr);
  2850. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  2851. ReturnValueSlot ReturnValue);
  2852. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  2853. const CXXMethodDecl *MD,
  2854. ReturnValueSlot ReturnValue);
  2855. RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
  2856. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  2857. ReturnValueSlot ReturnValue);
  2858. RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
  2859. ReturnValueSlot ReturnValue);
  2860. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  2861. unsigned BuiltinID, const CallExpr *E,
  2862. ReturnValueSlot ReturnValue);
  2863. /// Emit IR for __builtin_os_log_format.
  2864. RValue emitBuiltinOSLogFormat(const CallExpr &E);
  2865. llvm::Function *generateBuiltinOSLogHelperFunction(
  2866. const analyze_os_log::OSLogBufferLayout &Layout,
  2867. CharUnits BufferAlignment);
  2868. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  2869. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  2870. /// is unhandled by the current target.
  2871. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2872. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  2873. const llvm::CmpInst::Predicate Fp,
  2874. const llvm::CmpInst::Predicate Ip,
  2875. const llvm::Twine &Name = "");
  2876. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2877. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  2878. unsigned LLVMIntrinsic,
  2879. unsigned AltLLVMIntrinsic,
  2880. const char *NameHint,
  2881. unsigned Modifier,
  2882. const CallExpr *E,
  2883. SmallVectorImpl<llvm::Value *> &Ops,
  2884. Address PtrOp0, Address PtrOp1);
  2885. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  2886. unsigned Modifier, llvm::Type *ArgTy,
  2887. const CallExpr *E);
  2888. llvm::Value *EmitNeonCall(llvm::Function *F,
  2889. SmallVectorImpl<llvm::Value*> &O,
  2890. const char *name,
  2891. unsigned shift = 0, bool rightshift = false);
  2892. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  2893. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  2894. bool negateForRightShift);
  2895. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  2896. llvm::Type *Ty, bool usgn, const char *name);
  2897. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  2898. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2899. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  2900. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2901. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2902. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2903. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2904. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2905. llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
  2906. const CallExpr *E);
  2907. private:
  2908. enum class MSVCIntrin;
  2909. public:
  2910. llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
  2911. llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
  2912. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  2913. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  2914. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  2915. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  2916. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  2917. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  2918. const ObjCMethodDecl *MethodWithObjects);
  2919. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  2920. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  2921. ReturnValueSlot Return = ReturnValueSlot());
  2922. /// Retrieves the default cleanup kind for an ARC cleanup.
  2923. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  2924. CleanupKind getARCCleanupKind() {
  2925. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  2926. ? NormalAndEHCleanup : NormalCleanup;
  2927. }
  2928. // ARC primitives.
  2929. void EmitARCInitWeak(Address addr, llvm::Value *value);
  2930. void EmitARCDestroyWeak(Address addr);
  2931. llvm::Value *EmitARCLoadWeak(Address addr);
  2932. llvm::Value *EmitARCLoadWeakRetained(Address addr);
  2933. llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
  2934. void EmitARCCopyWeak(Address dst, Address src);
  2935. void EmitARCMoveWeak(Address dst, Address src);
  2936. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  2937. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  2938. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  2939. bool resultIgnored);
  2940. llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
  2941. bool resultIgnored);
  2942. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  2943. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  2944. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  2945. void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
  2946. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  2947. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  2948. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  2949. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  2950. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  2951. llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
  2952. std::pair<LValue,llvm::Value*>
  2953. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  2954. std::pair<LValue,llvm::Value*>
  2955. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  2956. std::pair<LValue,llvm::Value*>
  2957. EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
  2958. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  2959. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  2960. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  2961. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  2962. llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
  2963. bool allowUnsafeClaim);
  2964. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  2965. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  2966. llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
  2967. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  2968. static Destroyer destroyARCStrongImprecise;
  2969. static Destroyer destroyARCStrongPrecise;
  2970. static Destroyer destroyARCWeak;
  2971. static Destroyer emitARCIntrinsicUse;
  2972. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  2973. llvm::Value *EmitObjCAutoreleasePoolPush();
  2974. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  2975. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  2976. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  2977. /// \brief Emits a reference binding to the passed in expression.
  2978. RValue EmitReferenceBindingToExpr(const Expr *E);
  2979. //===--------------------------------------------------------------------===//
  2980. // Expression Emission
  2981. //===--------------------------------------------------------------------===//
  2982. // Expressions are broken into three classes: scalar, complex, aggregate.
  2983. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  2984. /// scalar type, returning the result.
  2985. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  2986. /// Emit a conversion from the specified type to the specified destination
  2987. /// type, both of which are LLVM scalar types.
  2988. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  2989. QualType DstTy, SourceLocation Loc);
  2990. /// Emit a conversion from the specified complex type to the specified
  2991. /// destination type, where the destination type is an LLVM scalar type.
  2992. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  2993. QualType DstTy,
  2994. SourceLocation Loc);
  2995. /// EmitAggExpr - Emit the computation of the specified expression
  2996. /// of aggregate type. The result is computed into the given slot,
  2997. /// which may be null to indicate that the value is not needed.
  2998. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  2999. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  3000. /// aggregate type into a temporary LValue.
  3001. LValue EmitAggExprToLValue(const Expr *E);
  3002. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  3003. /// make sure it survives garbage collection until this point.
  3004. void EmitExtendGCLifetime(llvm::Value *object);
  3005. /// EmitComplexExpr - Emit the computation of the specified expression of
  3006. /// complex type, returning the result.
  3007. ComplexPairTy EmitComplexExpr(const Expr *E,
  3008. bool IgnoreReal = false,
  3009. bool IgnoreImag = false);
  3010. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  3011. /// type and place its result into the specified l-value.
  3012. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  3013. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  3014. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  3015. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  3016. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  3017. Address emitAddrOfRealComponent(Address complex, QualType complexType);
  3018. Address emitAddrOfImagComponent(Address complex, QualType complexType);
  3019. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  3020. /// global variable that has already been created for it. If the initializer
  3021. /// has a different type than GV does, this may free GV and return a different
  3022. /// one. Otherwise it just returns GV.
  3023. llvm::GlobalVariable *
  3024. AddInitializerToStaticVarDecl(const VarDecl &D,
  3025. llvm::GlobalVariable *GV);
  3026. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  3027. /// variable with global storage.
  3028. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  3029. bool PerformInit);
  3030. llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
  3031. llvm::Constant *Addr);
  3032. /// Call atexit() with a function that passes the given argument to
  3033. /// the given function.
  3034. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
  3035. llvm::Constant *addr);
  3036. /// Emit code in this function to perform a guarded variable
  3037. /// initialization. Guarded initializations are used when it's not
  3038. /// possible to prove that an initialization will be done exactly
  3039. /// once, e.g. with a static local variable or a static data member
  3040. /// of a class template.
  3041. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  3042. bool PerformInit);
  3043. enum class GuardKind { VariableGuard, TlsGuard };
  3044. /// Emit a branch to select whether or not to perform guarded initialization.
  3045. void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
  3046. llvm::BasicBlock *InitBlock,
  3047. llvm::BasicBlock *NoInitBlock,
  3048. GuardKind Kind, const VarDecl *D);
  3049. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  3050. /// variables.
  3051. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  3052. ArrayRef<llvm::Function *> CXXThreadLocals,
  3053. Address Guard = Address::invalid());
  3054. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  3055. /// variables.
  3056. void GenerateCXXGlobalDtorsFunc(
  3057. llvm::Function *Fn,
  3058. const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
  3059. &DtorsAndObjects);
  3060. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  3061. const VarDecl *D,
  3062. llvm::GlobalVariable *Addr,
  3063. bool PerformInit);
  3064. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  3065. void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
  3066. void enterFullExpression(const ExprWithCleanups *E) {
  3067. if (E->getNumObjects() == 0) return;
  3068. enterNonTrivialFullExpression(E);
  3069. }
  3070. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  3071. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  3072. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  3073. RValue EmitAtomicExpr(AtomicExpr *E);
  3074. //===--------------------------------------------------------------------===//
  3075. // Annotations Emission
  3076. //===--------------------------------------------------------------------===//
  3077. /// Emit an annotation call (intrinsic or builtin).
  3078. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  3079. llvm::Value *AnnotatedVal,
  3080. StringRef AnnotationStr,
  3081. SourceLocation Location);
  3082. /// Emit local annotations for the local variable V, declared by D.
  3083. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  3084. /// Emit field annotations for the given field & value. Returns the
  3085. /// annotation result.
  3086. Address EmitFieldAnnotations(const FieldDecl *D, Address V);
  3087. //===--------------------------------------------------------------------===//
  3088. // Internal Helpers
  3089. //===--------------------------------------------------------------------===//
  3090. /// ContainsLabel - Return true if the statement contains a label in it. If
  3091. /// this statement is not executed normally, it not containing a label means
  3092. /// that we can just remove the code.
  3093. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  3094. /// containsBreak - Return true if the statement contains a break out of it.
  3095. /// If the statement (recursively) contains a switch or loop with a break
  3096. /// inside of it, this is fine.
  3097. static bool containsBreak(const Stmt *S);
  3098. /// Determine if the given statement might introduce a declaration into the
  3099. /// current scope, by being a (possibly-labelled) DeclStmt.
  3100. static bool mightAddDeclToScope(const Stmt *S);
  3101. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3102. /// to a constant, or if it does but contains a label, return false. If it
  3103. /// constant folds return true and set the boolean result in Result.
  3104. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
  3105. bool AllowLabels = false);
  3106. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  3107. /// to a constant, or if it does but contains a label, return false. If it
  3108. /// constant folds return true and set the folded value.
  3109. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
  3110. bool AllowLabels = false);
  3111. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  3112. /// if statement) to the specified blocks. Based on the condition, this might
  3113. /// try to simplify the codegen of the conditional based on the branch.
  3114. /// TrueCount should be the number of times we expect the condition to
  3115. /// evaluate to true based on PGO data.
  3116. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  3117. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  3118. /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
  3119. /// nonnull, if \p LHS is marked _Nonnull.
  3120. void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
  3121. /// An enumeration which makes it easier to specify whether or not an
  3122. /// operation is a subtraction.
  3123. enum { NotSubtraction = false, IsSubtraction = true };
  3124. /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
  3125. /// detect undefined behavior when the pointer overflow sanitizer is enabled.
  3126. /// \p SignedIndices indicates whether any of the GEP indices are signed.
  3127. /// \p IsSubtraction indicates whether the expression used to form the GEP
  3128. /// is a subtraction.
  3129. llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
  3130. ArrayRef<llvm::Value *> IdxList,
  3131. bool SignedIndices,
  3132. bool IsSubtraction,
  3133. SourceLocation Loc,
  3134. const Twine &Name = "");
  3135. /// Specifies which type of sanitizer check to apply when handling a
  3136. /// particular builtin.
  3137. enum BuiltinCheckKind {
  3138. BCK_CTZPassedZero,
  3139. BCK_CLZPassedZero,
  3140. };
  3141. /// Emits an argument for a call to a builtin. If the builtin sanitizer is
  3142. /// enabled, a runtime check specified by \p Kind is also emitted.
  3143. llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
  3144. /// \brief Emit a description of a type in a format suitable for passing to
  3145. /// a runtime sanitizer handler.
  3146. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  3147. /// \brief Convert a value into a format suitable for passing to a runtime
  3148. /// sanitizer handler.
  3149. llvm::Value *EmitCheckValue(llvm::Value *V);
  3150. /// \brief Emit a description of a source location in a format suitable for
  3151. /// passing to a runtime sanitizer handler.
  3152. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  3153. /// \brief Create a basic block that will call a handler function in a
  3154. /// sanitizer runtime with the provided arguments, and create a conditional
  3155. /// branch to it.
  3156. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  3157. SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
  3158. ArrayRef<llvm::Value *> DynamicArgs);
  3159. /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
  3160. /// if Cond if false.
  3161. void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
  3162. llvm::ConstantInt *TypeId, llvm::Value *Ptr,
  3163. ArrayRef<llvm::Constant *> StaticArgs);
  3164. /// \brief Create a basic block that will call the trap intrinsic, and emit a
  3165. /// conditional branch to it, for the -ftrapv checks.
  3166. void EmitTrapCheck(llvm::Value *Checked);
  3167. /// \brief Emit a call to trap or debugtrap and attach function attribute
  3168. /// "trap-func-name" if specified.
  3169. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  3170. /// \brief Emit a stub for the cross-DSO CFI check function.
  3171. void EmitCfiCheckStub();
  3172. /// \brief Emit a cross-DSO CFI failure handling function.
  3173. void EmitCfiCheckFail();
  3174. /// \brief Create a check for a function parameter that may potentially be
  3175. /// declared as non-null.
  3176. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  3177. AbstractCallee AC, unsigned ParmNum);
  3178. /// EmitCallArg - Emit a single call argument.
  3179. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  3180. /// EmitDelegateCallArg - We are performing a delegate call; that
  3181. /// is, the current function is delegating to another one. Produce
  3182. /// a r-value suitable for passing the given parameter.
  3183. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  3184. SourceLocation loc);
  3185. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  3186. /// point operation, expressed as the maximum relative error in ulp.
  3187. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  3188. private:
  3189. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  3190. void EmitReturnOfRValue(RValue RV, QualType Ty);
  3191. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  3192. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  3193. DeferredReplacements;
  3194. /// Set the address of a local variable.
  3195. void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
  3196. assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
  3197. LocalDeclMap.insert({VD, Addr});
  3198. }
  3199. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  3200. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  3201. ///
  3202. /// \param AI - The first function argument of the expansion.
  3203. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  3204. SmallVectorImpl<llvm::Value *>::iterator &AI);
  3205. /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
  3206. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  3207. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  3208. void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  3209. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  3210. unsigned &IRCallArgPos);
  3211. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  3212. const Expr *InputExpr, std::string &ConstraintStr);
  3213. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  3214. LValue InputValue, QualType InputType,
  3215. std::string &ConstraintStr,
  3216. SourceLocation Loc);
  3217. /// \brief Attempts to statically evaluate the object size of E. If that
  3218. /// fails, emits code to figure the size of E out for us. This is
  3219. /// pass_object_size aware.
  3220. ///
  3221. /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
  3222. llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
  3223. llvm::IntegerType *ResType,
  3224. llvm::Value *EmittedE);
  3225. /// \brief Emits the size of E, as required by __builtin_object_size. This
  3226. /// function is aware of pass_object_size parameters, and will act accordingly
  3227. /// if E is a parameter with the pass_object_size attribute.
  3228. llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
  3229. llvm::IntegerType *ResType,
  3230. llvm::Value *EmittedE);
  3231. public:
  3232. #ifndef NDEBUG
  3233. // Determine whether the given argument is an Objective-C method
  3234. // that may have type parameters in its signature.
  3235. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  3236. const DeclContext *dc = method->getDeclContext();
  3237. if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
  3238. return classDecl->getTypeParamListAsWritten();
  3239. }
  3240. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  3241. return catDecl->getTypeParamList();
  3242. }
  3243. return false;
  3244. }
  3245. template<typename T>
  3246. static bool isObjCMethodWithTypeParams(const T *) { return false; }
  3247. #endif
  3248. enum class EvaluationOrder {
  3249. ///! No language constraints on evaluation order.
  3250. Default,
  3251. ///! Language semantics require left-to-right evaluation.
  3252. ForceLeftToRight,
  3253. ///! Language semantics require right-to-left evaluation.
  3254. ForceRightToLeft
  3255. };
  3256. /// EmitCallArgs - Emit call arguments for a function.
  3257. template <typename T>
  3258. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  3259. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3260. AbstractCallee AC = AbstractCallee(),
  3261. unsigned ParamsToSkip = 0,
  3262. EvaluationOrder Order = EvaluationOrder::Default) {
  3263. SmallVector<QualType, 16> ArgTypes;
  3264. CallExpr::const_arg_iterator Arg = ArgRange.begin();
  3265. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  3266. "Can't skip parameters if type info is not provided");
  3267. if (CallArgTypeInfo) {
  3268. #ifndef NDEBUG
  3269. bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
  3270. #endif
  3271. // First, use the argument types that the type info knows about
  3272. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  3273. E = CallArgTypeInfo->param_type_end();
  3274. I != E; ++I, ++Arg) {
  3275. assert(Arg != ArgRange.end() && "Running over edge of argument list!");
  3276. assert((isGenericMethod ||
  3277. ((*I)->isVariablyModifiedType() ||
  3278. (*I).getNonReferenceType()->isObjCRetainableType() ||
  3279. getContext()
  3280. .getCanonicalType((*I).getNonReferenceType())
  3281. .getTypePtr() ==
  3282. getContext()
  3283. .getCanonicalType((*Arg)->getType())
  3284. .getTypePtr())) &&
  3285. "type mismatch in call argument!");
  3286. ArgTypes.push_back(*I);
  3287. }
  3288. }
  3289. // Either we've emitted all the call args, or we have a call to variadic
  3290. // function.
  3291. assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
  3292. CallArgTypeInfo->isVariadic()) &&
  3293. "Extra arguments in non-variadic function!");
  3294. // If we still have any arguments, emit them using the type of the argument.
  3295. for (auto *A : llvm::make_range(Arg, ArgRange.end()))
  3296. ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
  3297. EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
  3298. }
  3299. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  3300. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3301. AbstractCallee AC = AbstractCallee(),
  3302. unsigned ParamsToSkip = 0,
  3303. EvaluationOrder Order = EvaluationOrder::Default);
  3304. /// EmitPointerWithAlignment - Given an expression with a pointer type,
  3305. /// emit the value and compute our best estimate of the alignment of the
  3306. /// pointee.
  3307. ///
  3308. /// \param BaseInfo - If non-null, this will be initialized with
  3309. /// information about the source of the alignment and the may-alias
  3310. /// attribute. Note that this function will conservatively fall back on
  3311. /// the type when it doesn't recognize the expression and may-alias will
  3312. /// be set to false.
  3313. ///
  3314. /// One reasonable way to use this information is when there's a language
  3315. /// guarantee that the pointer must be aligned to some stricter value, and
  3316. /// we're simply trying to ensure that sufficiently obvious uses of under-
  3317. /// aligned objects don't get miscompiled; for example, a placement new
  3318. /// into the address of a local variable. In such a case, it's quite
  3319. /// reasonable to just ignore the returned alignment when it isn't from an
  3320. /// explicit source.
  3321. Address EmitPointerWithAlignment(const Expr *Addr,
  3322. LValueBaseInfo *BaseInfo = nullptr,
  3323. TBAAAccessInfo *TBAAInfo = nullptr);
  3324. /// If \p E references a parameter with pass_object_size info or a constant
  3325. /// array size modifier, emit the object size divided by the size of \p EltTy.
  3326. /// Otherwise return null.
  3327. llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
  3328. void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
  3329. private:
  3330. QualType getVarArgType(const Expr *Arg);
  3331. void EmitDeclMetadata();
  3332. BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
  3333. const AutoVarEmission &emission);
  3334. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  3335. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  3336. llvm::Value *EmitX86CpuIs(const CallExpr *E);
  3337. llvm::Value *EmitX86CpuIs(StringRef CPUStr);
  3338. llvm::Value *EmitX86CpuSupports(const CallExpr *E);
  3339. llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
  3340. llvm::Value *EmitX86CpuInit();
  3341. };
  3342. /// Helper class with most of the code for saving a value for a
  3343. /// conditional expression cleanup.
  3344. struct DominatingLLVMValue {
  3345. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  3346. /// Answer whether the given value needs extra work to be saved.
  3347. static bool needsSaving(llvm::Value *value) {
  3348. // If it's not an instruction, we don't need to save.
  3349. if (!isa<llvm::Instruction>(value)) return false;
  3350. // If it's an instruction in the entry block, we don't need to save.
  3351. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  3352. return (block != &block->getParent()->getEntryBlock());
  3353. }
  3354. /// Try to save the given value.
  3355. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  3356. if (!needsSaving(value)) return saved_type(value, false);
  3357. // Otherwise, we need an alloca.
  3358. auto align = CharUnits::fromQuantity(
  3359. CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
  3360. Address alloca =
  3361. CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
  3362. CGF.Builder.CreateStore(value, alloca);
  3363. return saved_type(alloca.getPointer(), true);
  3364. }
  3365. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  3366. // If the value says it wasn't saved, trust that it's still dominating.
  3367. if (!value.getInt()) return value.getPointer();
  3368. // Otherwise, it should be an alloca instruction, as set up in save().
  3369. auto alloca = cast<llvm::AllocaInst>(value.getPointer());
  3370. return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
  3371. }
  3372. };
  3373. /// A partial specialization of DominatingValue for llvm::Values that
  3374. /// might be llvm::Instructions.
  3375. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  3376. typedef T *type;
  3377. static type restore(CodeGenFunction &CGF, saved_type value) {
  3378. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  3379. }
  3380. };
  3381. /// A specialization of DominatingValue for Address.
  3382. template <> struct DominatingValue<Address> {
  3383. typedef Address type;
  3384. struct saved_type {
  3385. DominatingLLVMValue::saved_type SavedValue;
  3386. CharUnits Alignment;
  3387. };
  3388. static bool needsSaving(type value) {
  3389. return DominatingLLVMValue::needsSaving(value.getPointer());
  3390. }
  3391. static saved_type save(CodeGenFunction &CGF, type value) {
  3392. return { DominatingLLVMValue::save(CGF, value.getPointer()),
  3393. value.getAlignment() };
  3394. }
  3395. static type restore(CodeGenFunction &CGF, saved_type value) {
  3396. return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
  3397. value.Alignment);
  3398. }
  3399. };
  3400. /// A specialization of DominatingValue for RValue.
  3401. template <> struct DominatingValue<RValue> {
  3402. typedef RValue type;
  3403. class saved_type {
  3404. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  3405. AggregateAddress, ComplexAddress };
  3406. llvm::Value *Value;
  3407. unsigned K : 3;
  3408. unsigned Align : 29;
  3409. saved_type(llvm::Value *v, Kind k, unsigned a = 0)
  3410. : Value(v), K(k), Align(a) {}
  3411. public:
  3412. static bool needsSaving(RValue value);
  3413. static saved_type save(CodeGenFunction &CGF, RValue value);
  3414. RValue restore(CodeGenFunction &CGF);
  3415. // implementations in CGCleanup.cpp
  3416. };
  3417. static bool needsSaving(type value) {
  3418. return saved_type::needsSaving(value);
  3419. }
  3420. static saved_type save(CodeGenFunction &CGF, type value) {
  3421. return saved_type::save(CGF, value);
  3422. }
  3423. static type restore(CodeGenFunction &CGF, saved_type value) {
  3424. return value.restore(CGF);
  3425. }
  3426. };
  3427. } // end namespace CodeGen
  3428. } // end namespace clang
  3429. #endif