CodeGenFunction.h 156 KB

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