CodeGenFunction.h 137 KB

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