CodeGenFunction.h 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481
  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 CLANG_CODEGEN_CODEGENFUNCTION_H
  14. #define CLANG_CODEGEN_CODEGENFUNCTION_H
  15. #include "clang/AST/Type.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/ExprObjC.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/Frontend/CodeGenOptions.h"
  20. #include "clang/Basic/ABI.h"
  21. #include "clang/Basic/TargetInfo.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/Support/ValueHandle.h"
  26. #include "CodeGenModule.h"
  27. #include "CGBuilder.h"
  28. #include "CGValue.h"
  29. namespace llvm {
  30. class BasicBlock;
  31. class LLVMContext;
  32. class MDNode;
  33. class Module;
  34. class SwitchInst;
  35. class Twine;
  36. class Value;
  37. class CallSite;
  38. }
  39. namespace clang {
  40. class APValue;
  41. class ASTContext;
  42. class CXXDestructorDecl;
  43. class CXXForRangeStmt;
  44. class CXXTryStmt;
  45. class Decl;
  46. class LabelDecl;
  47. class EnumConstantDecl;
  48. class FunctionDecl;
  49. class FunctionProtoType;
  50. class LabelStmt;
  51. class ObjCContainerDecl;
  52. class ObjCInterfaceDecl;
  53. class ObjCIvarDecl;
  54. class ObjCMethodDecl;
  55. class ObjCImplementationDecl;
  56. class ObjCPropertyImplDecl;
  57. class TargetInfo;
  58. class TargetCodeGenInfo;
  59. class VarDecl;
  60. class ObjCForCollectionStmt;
  61. class ObjCAtTryStmt;
  62. class ObjCAtThrowStmt;
  63. class ObjCAtSynchronizedStmt;
  64. class ObjCAutoreleasePoolStmt;
  65. namespace CodeGen {
  66. class CodeGenTypes;
  67. class CGDebugInfo;
  68. class CGFunctionInfo;
  69. class CGRecordLayout;
  70. class CGBlockInfo;
  71. class CGCXXABI;
  72. class BlockFlags;
  73. class BlockFieldFlags;
  74. /// A branch fixup. These are required when emitting a goto to a
  75. /// label which hasn't been emitted yet. The goto is optimistically
  76. /// emitted as a branch to the basic block for the label, and (if it
  77. /// occurs in a scope with non-trivial cleanups) a fixup is added to
  78. /// the innermost cleanup. When a (normal) cleanup is popped, any
  79. /// unresolved fixups in that scope are threaded through the cleanup.
  80. struct BranchFixup {
  81. /// The block containing the terminator which needs to be modified
  82. /// into a switch if this fixup is resolved into the current scope.
  83. /// If null, LatestBranch points directly to the destination.
  84. llvm::BasicBlock *OptimisticBranchBlock;
  85. /// The ultimate destination of the branch.
  86. ///
  87. /// This can be set to null to indicate that this fixup was
  88. /// successfully resolved.
  89. llvm::BasicBlock *Destination;
  90. /// The destination index value.
  91. unsigned DestinationIndex;
  92. /// The initial branch of the fixup.
  93. llvm::BranchInst *InitialBranch;
  94. };
  95. template <class T> struct InvariantValue {
  96. typedef T type;
  97. typedef T saved_type;
  98. static bool needsSaving(type value) { return false; }
  99. static saved_type save(CodeGenFunction &CGF, type value) { return value; }
  100. static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
  101. };
  102. /// A metaprogramming class for ensuring that a value will dominate an
  103. /// arbitrary position in a function.
  104. template <class T> struct DominatingValue : InvariantValue<T> {};
  105. template <class T, bool mightBeInstruction =
  106. llvm::is_base_of<llvm::Value, T>::value &&
  107. !llvm::is_base_of<llvm::Constant, T>::value &&
  108. !llvm::is_base_of<llvm::BasicBlock, T>::value>
  109. struct DominatingPointer;
  110. template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
  111. // template <class T> struct DominatingPointer<T,true> at end of file
  112. template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
  113. enum CleanupKind {
  114. EHCleanup = 0x1,
  115. NormalCleanup = 0x2,
  116. NormalAndEHCleanup = EHCleanup | NormalCleanup,
  117. InactiveCleanup = 0x4,
  118. InactiveEHCleanup = EHCleanup | InactiveCleanup,
  119. InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
  120. InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
  121. };
  122. /// A stack of scopes which respond to exceptions, including cleanups
  123. /// and catch blocks.
  124. class EHScopeStack {
  125. public:
  126. /// A saved depth on the scope stack. This is necessary because
  127. /// pushing scopes onto the stack invalidates iterators.
  128. class stable_iterator {
  129. friend class EHScopeStack;
  130. /// Offset from StartOfData to EndOfBuffer.
  131. ptrdiff_t Size;
  132. stable_iterator(ptrdiff_t Size) : Size(Size) {}
  133. public:
  134. static stable_iterator invalid() { return stable_iterator(-1); }
  135. stable_iterator() : Size(-1) {}
  136. bool isValid() const { return Size >= 0; }
  137. /// Returns true if this scope encloses I.
  138. /// Returns false if I is invalid.
  139. /// This scope must be valid.
  140. bool encloses(stable_iterator I) const { return Size <= I.Size; }
  141. /// Returns true if this scope strictly encloses I: that is,
  142. /// if it encloses I and is not I.
  143. /// Returns false is I is invalid.
  144. /// This scope must be valid.
  145. bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
  146. friend bool operator==(stable_iterator A, stable_iterator B) {
  147. return A.Size == B.Size;
  148. }
  149. friend bool operator!=(stable_iterator A, stable_iterator B) {
  150. return A.Size != B.Size;
  151. }
  152. };
  153. /// Information for lazily generating a cleanup. Subclasses must be
  154. /// POD-like: cleanups will not be destructed, and they will be
  155. /// allocated on the cleanup stack and freely copied and moved
  156. /// around.
  157. ///
  158. /// Cleanup implementations should generally be declared in an
  159. /// anonymous namespace.
  160. class Cleanup {
  161. // Anchor the construction vtable.
  162. virtual void anchor();
  163. public:
  164. /// Generation flags.
  165. class Flags {
  166. enum {
  167. F_IsForEH = 0x1,
  168. F_IsNormalCleanupKind = 0x2,
  169. F_IsEHCleanupKind = 0x4
  170. };
  171. unsigned flags;
  172. public:
  173. Flags() : flags(0) {}
  174. /// isForEH - true if the current emission is for an EH cleanup.
  175. bool isForEHCleanup() const { return flags & F_IsForEH; }
  176. bool isForNormalCleanup() const { return !isForEHCleanup(); }
  177. void setIsForEHCleanup() { flags |= F_IsForEH; }
  178. bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
  179. void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
  180. /// isEHCleanupKind - true if the cleanup was pushed as an EH
  181. /// cleanup.
  182. bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
  183. void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
  184. };
  185. // Provide a virtual destructor to suppress a very common warning
  186. // that unfortunately cannot be suppressed without this. Cleanups
  187. // should not rely on this destructor ever being called.
  188. virtual ~Cleanup() {}
  189. /// Emit the cleanup. For normal cleanups, this is run in the
  190. /// same EH context as when the cleanup was pushed, i.e. the
  191. /// immediately-enclosing context of the cleanup scope. For
  192. /// EH cleanups, this is run in a terminate context.
  193. ///
  194. // \param IsForEHCleanup true if this is for an EH cleanup, false
  195. /// if for a normal cleanup.
  196. virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
  197. };
  198. /// ConditionalCleanupN stores the saved form of its N parameters,
  199. /// then restores them and performs the cleanup.
  200. template <class T, class A0>
  201. class ConditionalCleanup1 : public Cleanup {
  202. typedef typename DominatingValue<A0>::saved_type A0_saved;
  203. A0_saved a0_saved;
  204. void Emit(CodeGenFunction &CGF, Flags flags) {
  205. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  206. T(a0).Emit(CGF, flags);
  207. }
  208. public:
  209. ConditionalCleanup1(A0_saved a0)
  210. : a0_saved(a0) {}
  211. };
  212. template <class T, class A0, class A1>
  213. class ConditionalCleanup2 : public Cleanup {
  214. typedef typename DominatingValue<A0>::saved_type A0_saved;
  215. typedef typename DominatingValue<A1>::saved_type A1_saved;
  216. A0_saved a0_saved;
  217. A1_saved a1_saved;
  218. void Emit(CodeGenFunction &CGF, Flags flags) {
  219. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  220. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  221. T(a0, a1).Emit(CGF, flags);
  222. }
  223. public:
  224. ConditionalCleanup2(A0_saved a0, A1_saved a1)
  225. : a0_saved(a0), a1_saved(a1) {}
  226. };
  227. template <class T, class A0, class A1, class A2>
  228. class ConditionalCleanup3 : public Cleanup {
  229. typedef typename DominatingValue<A0>::saved_type A0_saved;
  230. typedef typename DominatingValue<A1>::saved_type A1_saved;
  231. typedef typename DominatingValue<A2>::saved_type A2_saved;
  232. A0_saved a0_saved;
  233. A1_saved a1_saved;
  234. A2_saved a2_saved;
  235. void Emit(CodeGenFunction &CGF, Flags flags) {
  236. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  237. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  238. A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
  239. T(a0, a1, a2).Emit(CGF, flags);
  240. }
  241. public:
  242. ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
  243. : a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
  244. };
  245. template <class T, class A0, class A1, class A2, class A3>
  246. class ConditionalCleanup4 : public Cleanup {
  247. typedef typename DominatingValue<A0>::saved_type A0_saved;
  248. typedef typename DominatingValue<A1>::saved_type A1_saved;
  249. typedef typename DominatingValue<A2>::saved_type A2_saved;
  250. typedef typename DominatingValue<A3>::saved_type A3_saved;
  251. A0_saved a0_saved;
  252. A1_saved a1_saved;
  253. A2_saved a2_saved;
  254. A3_saved a3_saved;
  255. void Emit(CodeGenFunction &CGF, Flags flags) {
  256. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  257. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  258. A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
  259. A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
  260. T(a0, a1, a2, a3).Emit(CGF, flags);
  261. }
  262. public:
  263. ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
  264. : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
  265. };
  266. private:
  267. // The implementation for this class is in CGException.h and
  268. // CGException.cpp; the definition is here because it's used as a
  269. // member of CodeGenFunction.
  270. /// The start of the scope-stack buffer, i.e. the allocated pointer
  271. /// for the buffer. All of these pointers are either simultaneously
  272. /// null or simultaneously valid.
  273. char *StartOfBuffer;
  274. /// The end of the buffer.
  275. char *EndOfBuffer;
  276. /// The first valid entry in the buffer.
  277. char *StartOfData;
  278. /// The innermost normal cleanup on the stack.
  279. stable_iterator InnermostNormalCleanup;
  280. /// The innermost EH scope on the stack.
  281. stable_iterator InnermostEHScope;
  282. /// The current set of branch fixups. A branch fixup is a jump to
  283. /// an as-yet unemitted label, i.e. a label for which we don't yet
  284. /// know the EH stack depth. Whenever we pop a cleanup, we have
  285. /// to thread all the current branch fixups through it.
  286. ///
  287. /// Fixups are recorded as the Use of the respective branch or
  288. /// switch statement. The use points to the final destination.
  289. /// When popping out of a cleanup, these uses are threaded through
  290. /// the cleanup and adjusted to point to the new cleanup.
  291. ///
  292. /// Note that branches are allowed to jump into protected scopes
  293. /// in certain situations; e.g. the following code is legal:
  294. /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
  295. /// goto foo;
  296. /// A a;
  297. /// foo:
  298. /// bar();
  299. SmallVector<BranchFixup, 8> BranchFixups;
  300. char *allocate(size_t Size);
  301. void *pushCleanup(CleanupKind K, size_t DataSize);
  302. public:
  303. EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
  304. InnermostNormalCleanup(stable_end()),
  305. InnermostEHScope(stable_end()) {}
  306. ~EHScopeStack() { delete[] StartOfBuffer; }
  307. // Variadic templates would make this not terrible.
  308. /// Push a lazily-created cleanup on the stack.
  309. template <class T>
  310. void pushCleanup(CleanupKind Kind) {
  311. void *Buffer = pushCleanup(Kind, sizeof(T));
  312. Cleanup *Obj = new(Buffer) T();
  313. (void) Obj;
  314. }
  315. /// Push a lazily-created cleanup on the stack.
  316. template <class T, class A0>
  317. void pushCleanup(CleanupKind Kind, A0 a0) {
  318. void *Buffer = pushCleanup(Kind, sizeof(T));
  319. Cleanup *Obj = new(Buffer) T(a0);
  320. (void) Obj;
  321. }
  322. /// Push a lazily-created cleanup on the stack.
  323. template <class T, class A0, class A1>
  324. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
  325. void *Buffer = pushCleanup(Kind, sizeof(T));
  326. Cleanup *Obj = new(Buffer) T(a0, a1);
  327. (void) Obj;
  328. }
  329. /// Push a lazily-created cleanup on the stack.
  330. template <class T, class A0, class A1, class A2>
  331. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
  332. void *Buffer = pushCleanup(Kind, sizeof(T));
  333. Cleanup *Obj = new(Buffer) T(a0, a1, a2);
  334. (void) Obj;
  335. }
  336. /// Push a lazily-created cleanup on the stack.
  337. template <class T, class A0, class A1, class A2, class A3>
  338. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  339. void *Buffer = pushCleanup(Kind, sizeof(T));
  340. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
  341. (void) Obj;
  342. }
  343. /// Push a lazily-created cleanup on the stack.
  344. template <class T, class A0, class A1, class A2, class A3, class A4>
  345. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
  346. void *Buffer = pushCleanup(Kind, sizeof(T));
  347. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
  348. (void) Obj;
  349. }
  350. // Feel free to add more variants of the following:
  351. /// Push a cleanup with non-constant storage requirements on the
  352. /// stack. The cleanup type must provide an additional static method:
  353. /// static size_t getExtraSize(size_t);
  354. /// The argument to this method will be the value N, which will also
  355. /// be passed as the first argument to the constructor.
  356. ///
  357. /// The data stored in the extra storage must obey the same
  358. /// restrictions as normal cleanup member data.
  359. ///
  360. /// The pointer returned from this method is valid until the cleanup
  361. /// stack is modified.
  362. template <class T, class A0, class A1, class A2>
  363. T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
  364. void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
  365. return new (Buffer) T(N, a0, a1, a2);
  366. }
  367. /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
  368. void popCleanup();
  369. /// Push a set of catch handlers on the stack. The catch is
  370. /// uninitialized and will need to have the given number of handlers
  371. /// set on it.
  372. class EHCatchScope *pushCatch(unsigned NumHandlers);
  373. /// Pops a catch scope off the stack. This is private to CGException.cpp.
  374. void popCatch();
  375. /// Push an exceptions filter on the stack.
  376. class EHFilterScope *pushFilter(unsigned NumFilters);
  377. /// Pops an exceptions filter off the stack.
  378. void popFilter();
  379. /// Push a terminate handler on the stack.
  380. void pushTerminate();
  381. /// Pops a terminate handler off the stack.
  382. void popTerminate();
  383. /// Determines whether the exception-scopes stack is empty.
  384. bool empty() const { return StartOfData == EndOfBuffer; }
  385. bool requiresLandingPad() const {
  386. return InnermostEHScope != stable_end();
  387. }
  388. /// Determines whether there are any normal cleanups on the stack.
  389. bool hasNormalCleanups() const {
  390. return InnermostNormalCleanup != stable_end();
  391. }
  392. /// Returns the innermost normal cleanup on the stack, or
  393. /// stable_end() if there are no normal cleanups.
  394. stable_iterator getInnermostNormalCleanup() const {
  395. return InnermostNormalCleanup;
  396. }
  397. stable_iterator getInnermostActiveNormalCleanup() const;
  398. stable_iterator getInnermostEHScope() const {
  399. return InnermostEHScope;
  400. }
  401. stable_iterator getInnermostActiveEHScope() const;
  402. /// An unstable reference to a scope-stack depth. Invalidated by
  403. /// pushes but not pops.
  404. class iterator;
  405. /// Returns an iterator pointing to the innermost EH scope.
  406. iterator begin() const;
  407. /// Returns an iterator pointing to the outermost EH scope.
  408. iterator end() const;
  409. /// Create a stable reference to the top of the EH stack. The
  410. /// returned reference is valid until that scope is popped off the
  411. /// stack.
  412. stable_iterator stable_begin() const {
  413. return stable_iterator(EndOfBuffer - StartOfData);
  414. }
  415. /// Create a stable reference to the bottom of the EH stack.
  416. static stable_iterator stable_end() {
  417. return stable_iterator(0);
  418. }
  419. /// Translates an iterator into a stable_iterator.
  420. stable_iterator stabilize(iterator it) const;
  421. /// Turn a stable reference to a scope depth into a unstable pointer
  422. /// to the EH stack.
  423. iterator find(stable_iterator save) const;
  424. /// Removes the cleanup pointed to by the given stable_iterator.
  425. void removeCleanup(stable_iterator save);
  426. /// Add a branch fixup to the current cleanup scope.
  427. BranchFixup &addBranchFixup() {
  428. assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
  429. BranchFixups.push_back(BranchFixup());
  430. return BranchFixups.back();
  431. }
  432. unsigned getNumBranchFixups() const { return BranchFixups.size(); }
  433. BranchFixup &getBranchFixup(unsigned I) {
  434. assert(I < getNumBranchFixups());
  435. return BranchFixups[I];
  436. }
  437. /// Pops lazily-removed fixups from the end of the list. This
  438. /// should only be called by procedures which have just popped a
  439. /// cleanup or resolved one or more fixups.
  440. void popNullFixups();
  441. /// Clears the branch-fixups list. This should only be called by
  442. /// ResolveAllBranchFixups.
  443. void clearFixups() { BranchFixups.clear(); }
  444. };
  445. /// CodeGenFunction - This class organizes the per-function state that is used
  446. /// while generating LLVM code.
  447. class CodeGenFunction : public CodeGenTypeCache {
  448. CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
  449. void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT
  450. friend class CGCXXABI;
  451. public:
  452. /// A jump destination is an abstract label, branching to which may
  453. /// require a jump out through normal cleanups.
  454. struct JumpDest {
  455. JumpDest() : Block(0), ScopeDepth(), Index(0) {}
  456. JumpDest(llvm::BasicBlock *Block,
  457. EHScopeStack::stable_iterator Depth,
  458. unsigned Index)
  459. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  460. bool isValid() const { return Block != 0; }
  461. llvm::BasicBlock *getBlock() const { return Block; }
  462. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  463. unsigned getDestIndex() const { return Index; }
  464. private:
  465. llvm::BasicBlock *Block;
  466. EHScopeStack::stable_iterator ScopeDepth;
  467. unsigned Index;
  468. };
  469. CodeGenModule &CGM; // Per-module state.
  470. const TargetInfo &Target;
  471. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  472. CGBuilderTy Builder;
  473. /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
  474. /// This excludes BlockDecls.
  475. const Decl *CurFuncDecl;
  476. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  477. const Decl *CurCodeDecl;
  478. const CGFunctionInfo *CurFnInfo;
  479. QualType FnRetTy;
  480. llvm::Function *CurFn;
  481. /// CurGD - The GlobalDecl for the current function being compiled.
  482. GlobalDecl CurGD;
  483. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  484. /// cleanups associated with the parameters.
  485. EHScopeStack::stable_iterator PrologueCleanupDepth;
  486. /// ReturnBlock - Unified return block.
  487. JumpDest ReturnBlock;
  488. /// ReturnValue - The temporary alloca to hold the return value. This is null
  489. /// iff the function has no return value.
  490. llvm::Value *ReturnValue;
  491. /// AllocaInsertPoint - This is an instruction in the entry block before which
  492. /// we prefer to insert allocas.
  493. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  494. bool CatchUndefined;
  495. /// In ARC, whether we should autorelease the return value.
  496. bool AutoreleaseResult;
  497. const CodeGen::CGBlockInfo *BlockInfo;
  498. llvm::Value *BlockPointer;
  499. /// \brief A mapping from NRVO variables to the flags used to indicate
  500. /// when the NRVO has been applied to this variable.
  501. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  502. EHScopeStack EHStack;
  503. /// i32s containing the indexes of the cleanup destinations.
  504. llvm::AllocaInst *NormalCleanupDest;
  505. unsigned NextCleanupDestIndex;
  506. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  507. llvm::BasicBlock *EHResumeBlock;
  508. /// The exception slot. All landing pads write the current
  509. /// exception pointer into this alloca.
  510. llvm::Value *ExceptionSlot;
  511. /// The selector slot. Under the MandatoryCleanup model, all
  512. /// landing pads write the current selector value into this alloca.
  513. llvm::AllocaInst *EHSelectorSlot;
  514. /// Emits a landing pad for the current EH stack.
  515. llvm::BasicBlock *EmitLandingPad();
  516. llvm::BasicBlock *getInvokeDestImpl();
  517. /// Set up the last cleaup that was pushed as a conditional
  518. /// full-expression cleanup.
  519. void initFullExprCleanup();
  520. template <class T>
  521. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  522. return DominatingValue<T>::save(*this, value);
  523. }
  524. public:
  525. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  526. /// rethrows.
  527. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  528. /// A class controlling the emission of a finally block.
  529. class FinallyInfo {
  530. /// Where the catchall's edge through the cleanup should go.
  531. JumpDest RethrowDest;
  532. /// A function to call to enter the catch.
  533. llvm::Constant *BeginCatchFn;
  534. /// An i1 variable indicating whether or not the @finally is
  535. /// running for an exception.
  536. llvm::AllocaInst *ForEHVar;
  537. /// An i8* variable into which the exception pointer to rethrow
  538. /// has been saved.
  539. llvm::AllocaInst *SavedExnVar;
  540. public:
  541. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  542. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  543. llvm::Constant *rethrowFn);
  544. void exit(CodeGenFunction &CGF);
  545. };
  546. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  547. /// current full-expression. Safe against the possibility that
  548. /// we're currently inside a conditionally-evaluated expression.
  549. template <class T, class A0>
  550. void pushFullExprCleanup(CleanupKind kind, A0 a0) {
  551. // If we're not in a conditional branch, or if none of the
  552. // arguments requires saving, then use the unconditional cleanup.
  553. if (!isInConditionalBranch())
  554. return EHStack.pushCleanup<T>(kind, a0);
  555. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  556. typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
  557. EHStack.pushCleanup<CleanupType>(kind, a0_saved);
  558. initFullExprCleanup();
  559. }
  560. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  561. /// current full-expression. Safe against the possibility that
  562. /// we're currently inside a conditionally-evaluated expression.
  563. template <class T, class A0, class A1>
  564. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
  565. // If we're not in a conditional branch, or if none of the
  566. // arguments requires saving, then use the unconditional cleanup.
  567. if (!isInConditionalBranch())
  568. return EHStack.pushCleanup<T>(kind, a0, a1);
  569. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  570. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  571. typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
  572. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
  573. initFullExprCleanup();
  574. }
  575. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  576. /// current full-expression. Safe against the possibility that
  577. /// we're currently inside a conditionally-evaluated expression.
  578. template <class T, class A0, class A1, class A2>
  579. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
  580. // If we're not in a conditional branch, or if none of the
  581. // arguments requires saving, then use the unconditional cleanup.
  582. if (!isInConditionalBranch()) {
  583. return EHStack.pushCleanup<T>(kind, a0, a1, a2);
  584. }
  585. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  586. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  587. typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
  588. typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
  589. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
  590. initFullExprCleanup();
  591. }
  592. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  593. /// current full-expression. Safe against the possibility that
  594. /// we're currently inside a conditionally-evaluated expression.
  595. template <class T, class A0, class A1, class A2, class A3>
  596. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  597. // If we're not in a conditional branch, or if none of the
  598. // arguments requires saving, then use the unconditional cleanup.
  599. if (!isInConditionalBranch()) {
  600. return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
  601. }
  602. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  603. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  604. typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
  605. typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
  606. typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
  607. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
  608. a2_saved, a3_saved);
  609. initFullExprCleanup();
  610. }
  611. /// PushDestructorCleanup - Push a cleanup to call the
  612. /// complete-object destructor of an object of the given type at the
  613. /// given address. Does nothing if T is not a C++ class type with a
  614. /// non-trivial destructor.
  615. void PushDestructorCleanup(QualType T, llvm::Value *Addr);
  616. /// PushDestructorCleanup - Push a cleanup to call the
  617. /// complete-object variant of the given destructor on the object at
  618. /// the given address.
  619. void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
  620. llvm::Value *Addr);
  621. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  622. /// process all branch fixups.
  623. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  624. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  625. /// The block cannot be reactivated. Pops it if it's the top of the
  626. /// stack.
  627. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
  628. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  629. /// Cannot be used to resurrect a deactivated cleanup.
  630. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
  631. /// \brief Enters a new scope for capturing cleanups, all of which
  632. /// will be executed once the scope is exited.
  633. class RunCleanupsScope {
  634. CodeGenFunction& CGF;
  635. EHScopeStack::stable_iterator CleanupStackDepth;
  636. bool OldDidCallStackSave;
  637. bool PerformCleanup;
  638. RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
  639. RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
  640. public:
  641. /// \brief Enter a new cleanup scope.
  642. explicit RunCleanupsScope(CodeGenFunction &CGF)
  643. : CGF(CGF), PerformCleanup(true)
  644. {
  645. CleanupStackDepth = CGF.EHStack.stable_begin();
  646. OldDidCallStackSave = CGF.DidCallStackSave;
  647. CGF.DidCallStackSave = false;
  648. }
  649. /// \brief Exit this cleanup scope, emitting any accumulated
  650. /// cleanups.
  651. ~RunCleanupsScope() {
  652. if (PerformCleanup) {
  653. CGF.DidCallStackSave = OldDidCallStackSave;
  654. CGF.PopCleanupBlocks(CleanupStackDepth);
  655. }
  656. }
  657. /// \brief Determine whether this scope requires any cleanups.
  658. bool requiresCleanups() const {
  659. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  660. }
  661. /// \brief Force the emission of cleanups now, instead of waiting
  662. /// until this object is destroyed.
  663. void ForceCleanup() {
  664. assert(PerformCleanup && "Already forced cleanup");
  665. CGF.DidCallStackSave = OldDidCallStackSave;
  666. CGF.PopCleanupBlocks(CleanupStackDepth);
  667. PerformCleanup = false;
  668. }
  669. };
  670. /// PopCleanupBlocks - Takes the old cleanup stack size and emits
  671. /// the cleanup blocks that have been added.
  672. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  673. void ResolveBranchFixups(llvm::BasicBlock *Target);
  674. /// The given basic block lies in the current EH scope, but may be a
  675. /// target of a potentially scope-crossing jump; get a stable handle
  676. /// to which we can perform this jump later.
  677. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  678. return JumpDest(Target,
  679. EHStack.getInnermostNormalCleanup(),
  680. NextCleanupDestIndex++);
  681. }
  682. /// The given basic block lies in the current EH scope, but may be a
  683. /// target of a potentially scope-crossing jump; get a stable handle
  684. /// to which we can perform this jump later.
  685. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  686. return getJumpDestInCurrentScope(createBasicBlock(Name));
  687. }
  688. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  689. /// block through the normal cleanup handling code (if any) and then
  690. /// on to \arg Dest.
  691. void EmitBranchThroughCleanup(JumpDest Dest);
  692. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  693. /// specified destination obviously has no cleanups to run. 'false' is always
  694. /// a conservatively correct answer for this method.
  695. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  696. /// popCatchScope - Pops the catch scope at the top of the EHScope
  697. /// stack, emitting any required code (other than the catch handlers
  698. /// themselves).
  699. void popCatchScope();
  700. llvm::BasicBlock *getEHResumeBlock();
  701. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  702. /// An object to manage conditionally-evaluated expressions.
  703. class ConditionalEvaluation {
  704. llvm::BasicBlock *StartBB;
  705. public:
  706. ConditionalEvaluation(CodeGenFunction &CGF)
  707. : StartBB(CGF.Builder.GetInsertBlock()) {}
  708. void begin(CodeGenFunction &CGF) {
  709. assert(CGF.OutermostConditional != this);
  710. if (!CGF.OutermostConditional)
  711. CGF.OutermostConditional = this;
  712. }
  713. void end(CodeGenFunction &CGF) {
  714. assert(CGF.OutermostConditional != 0);
  715. if (CGF.OutermostConditional == this)
  716. CGF.OutermostConditional = 0;
  717. }
  718. /// Returns a block which will be executed prior to each
  719. /// evaluation of the conditional code.
  720. llvm::BasicBlock *getStartingBlock() const {
  721. return StartBB;
  722. }
  723. };
  724. /// isInConditionalBranch - Return true if we're currently emitting
  725. /// one branch or the other of a conditional expression.
  726. bool isInConditionalBranch() const { return OutermostConditional != 0; }
  727. /// An RAII object to record that we're evaluating a statement
  728. /// expression.
  729. class StmtExprEvaluation {
  730. CodeGenFunction &CGF;
  731. /// We have to save the outermost conditional: cleanups in a
  732. /// statement expression aren't conditional just because the
  733. /// StmtExpr is.
  734. ConditionalEvaluation *SavedOutermostConditional;
  735. public:
  736. StmtExprEvaluation(CodeGenFunction &CGF)
  737. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  738. CGF.OutermostConditional = 0;
  739. }
  740. ~StmtExprEvaluation() {
  741. CGF.OutermostConditional = SavedOutermostConditional;
  742. CGF.EnsureInsertPoint();
  743. }
  744. };
  745. /// An object which temporarily prevents a value from being
  746. /// destroyed by aggressive peephole optimizations that assume that
  747. /// all uses of a value have been realized in the IR.
  748. class PeepholeProtection {
  749. llvm::Instruction *Inst;
  750. friend class CodeGenFunction;
  751. public:
  752. PeepholeProtection() : Inst(0) {}
  753. };
  754. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  755. class OpaqueValueMapping {
  756. CodeGenFunction &CGF;
  757. const OpaqueValueExpr *OpaqueValue;
  758. bool BoundLValue;
  759. CodeGenFunction::PeepholeProtection Protection;
  760. public:
  761. static bool shouldBindAsLValue(const Expr *expr) {
  762. return expr->isGLValue() || expr->getType()->isRecordType();
  763. }
  764. /// Build the opaque value mapping for the given conditional
  765. /// operator if it's the GNU ?: extension. This is a common
  766. /// enough pattern that the convenience operator is really
  767. /// helpful.
  768. ///
  769. OpaqueValueMapping(CodeGenFunction &CGF,
  770. const AbstractConditionalOperator *op) : CGF(CGF) {
  771. if (isa<ConditionalOperator>(op)) {
  772. OpaqueValue = 0;
  773. BoundLValue = false;
  774. return;
  775. }
  776. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  777. init(e->getOpaqueValue(), e->getCommon());
  778. }
  779. OpaqueValueMapping(CodeGenFunction &CGF,
  780. const OpaqueValueExpr *opaqueValue,
  781. LValue lvalue)
  782. : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(true) {
  783. assert(opaqueValue && "no opaque value expression!");
  784. assert(shouldBindAsLValue(opaqueValue));
  785. initLValue(lvalue);
  786. }
  787. OpaqueValueMapping(CodeGenFunction &CGF,
  788. const OpaqueValueExpr *opaqueValue,
  789. RValue rvalue)
  790. : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(false) {
  791. assert(opaqueValue && "no opaque value expression!");
  792. assert(!shouldBindAsLValue(opaqueValue));
  793. initRValue(rvalue);
  794. }
  795. void pop() {
  796. assert(OpaqueValue && "mapping already popped!");
  797. popImpl();
  798. OpaqueValue = 0;
  799. }
  800. ~OpaqueValueMapping() {
  801. if (OpaqueValue) popImpl();
  802. }
  803. private:
  804. void popImpl() {
  805. if (BoundLValue)
  806. CGF.OpaqueLValues.erase(OpaqueValue);
  807. else {
  808. CGF.OpaqueRValues.erase(OpaqueValue);
  809. CGF.unprotectFromPeepholes(Protection);
  810. }
  811. }
  812. void init(const OpaqueValueExpr *ov, const Expr *e) {
  813. OpaqueValue = ov;
  814. BoundLValue = shouldBindAsLValue(ov);
  815. assert(BoundLValue == shouldBindAsLValue(e)
  816. && "inconsistent expression value kinds!");
  817. if (BoundLValue)
  818. initLValue(CGF.EmitLValue(e));
  819. else
  820. initRValue(CGF.EmitAnyExpr(e));
  821. }
  822. void initLValue(const LValue &lv) {
  823. CGF.OpaqueLValues.insert(std::make_pair(OpaqueValue, lv));
  824. }
  825. void initRValue(const RValue &rv) {
  826. // Work around an extremely aggressive peephole optimization in
  827. // EmitScalarConversion which assumes that all other uses of a
  828. // value are extant.
  829. Protection = CGF.protectFromPeepholes(rv);
  830. CGF.OpaqueRValues.insert(std::make_pair(OpaqueValue, rv));
  831. }
  832. };
  833. /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
  834. /// number that holds the value.
  835. unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
  836. /// BuildBlockByrefAddress - Computes address location of the
  837. /// variable which is declared as __block.
  838. llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
  839. const VarDecl *V);
  840. private:
  841. CGDebugInfo *DebugInfo;
  842. bool DisableDebugInfo;
  843. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  844. /// calling llvm.stacksave for multiple VLAs in the same scope.
  845. bool DidCallStackSave;
  846. /// IndirectBranch - The first time an indirect goto is seen we create a block
  847. /// with an indirect branch. Every time we see the address of a label taken,
  848. /// we add the label to the indirect goto. Every subsequent indirect goto is
  849. /// codegen'd as a jump to the IndirectBranch's basic block.
  850. llvm::IndirectBrInst *IndirectBranch;
  851. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  852. /// decls.
  853. typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
  854. DeclMapTy LocalDeclMap;
  855. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  856. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  857. // BreakContinueStack - This keeps track of where break and continue
  858. // statements should jump to.
  859. struct BreakContinue {
  860. BreakContinue(JumpDest Break, JumpDest Continue)
  861. : BreakBlock(Break), ContinueBlock(Continue) {}
  862. JumpDest BreakBlock;
  863. JumpDest ContinueBlock;
  864. };
  865. SmallVector<BreakContinue, 8> BreakContinueStack;
  866. /// SwitchInsn - This is nearest current switch instruction. It is null if if
  867. /// current context is not in a switch.
  868. llvm::SwitchInst *SwitchInsn;
  869. /// CaseRangeBlock - This block holds if condition check for last case
  870. /// statement range in current switch instruction.
  871. llvm::BasicBlock *CaseRangeBlock;
  872. /// OpaqueLValues - Keeps track of the current set of opaque value
  873. /// expressions.
  874. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  875. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  876. // VLASizeMap - This keeps track of the associated size for each VLA type.
  877. // We track this by the size expression rather than the type itself because
  878. // in certain situations, like a const qualifier applied to an VLA typedef,
  879. // multiple VLA types can share the same size expression.
  880. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  881. // enter/leave scopes.
  882. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  883. /// A block containing a single 'unreachable' instruction. Created
  884. /// lazily by getUnreachableBlock().
  885. llvm::BasicBlock *UnreachableBlock;
  886. /// CXXThisDecl - When generating code for a C++ member function,
  887. /// this will hold the implicit 'this' declaration.
  888. ImplicitParamDecl *CXXThisDecl;
  889. llvm::Value *CXXThisValue;
  890. /// CXXVTTDecl - When generating code for a base object constructor or
  891. /// base object destructor with virtual bases, this will hold the implicit
  892. /// VTT parameter.
  893. ImplicitParamDecl *CXXVTTDecl;
  894. llvm::Value *CXXVTTValue;
  895. /// OutermostConditional - Points to the outermost active
  896. /// conditional control. This is used so that we know if a
  897. /// temporary should be destroyed conditionally.
  898. ConditionalEvaluation *OutermostConditional;
  899. /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
  900. /// type as well as the field number that contains the actual data.
  901. llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
  902. unsigned> > ByRefValueInfo;
  903. llvm::BasicBlock *TerminateLandingPad;
  904. llvm::BasicBlock *TerminateHandler;
  905. llvm::BasicBlock *TrapBB;
  906. public:
  907. CodeGenFunction(CodeGenModule &cgm);
  908. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  909. ASTContext &getContext() const { return CGM.getContext(); }
  910. CGDebugInfo *getDebugInfo() {
  911. if (DisableDebugInfo)
  912. return NULL;
  913. return DebugInfo;
  914. }
  915. void disableDebugInfo() { DisableDebugInfo = true; }
  916. void enableDebugInfo() { DisableDebugInfo = false; }
  917. bool shouldUseFusedARCCalls() {
  918. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  919. }
  920. const LangOptions &getLangOptions() const { return CGM.getLangOptions(); }
  921. /// Returns a pointer to the function's exception object slot, which
  922. /// is assigned in every landing pad.
  923. llvm::Value *getExceptionSlot();
  924. llvm::Value *getEHSelectorSlot();
  925. llvm::Value *getNormalCleanupDestSlot();
  926. llvm::BasicBlock *getUnreachableBlock() {
  927. if (!UnreachableBlock) {
  928. UnreachableBlock = createBasicBlock("unreachable");
  929. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  930. }
  931. return UnreachableBlock;
  932. }
  933. llvm::BasicBlock *getInvokeDest() {
  934. if (!EHStack.requiresLandingPad()) return 0;
  935. return getInvokeDestImpl();
  936. }
  937. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  938. //===--------------------------------------------------------------------===//
  939. // Cleanups
  940. //===--------------------------------------------------------------------===//
  941. typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
  942. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  943. llvm::Value *arrayEndPointer,
  944. QualType elementType,
  945. Destroyer &destroyer);
  946. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  947. llvm::Value *arrayEnd,
  948. QualType elementType,
  949. Destroyer &destroyer);
  950. void pushDestroy(QualType::DestructionKind dtorKind,
  951. llvm::Value *addr, QualType type);
  952. void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
  953. Destroyer &destroyer, bool useEHCleanupForArray);
  954. void emitDestroy(llvm::Value *addr, QualType type, Destroyer &destroyer,
  955. bool useEHCleanupForArray);
  956. llvm::Function *generateDestroyHelper(llvm::Constant *addr,
  957. QualType type,
  958. Destroyer &destroyer,
  959. bool useEHCleanupForArray);
  960. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  961. QualType type, Destroyer &destroyer,
  962. bool checkZeroLength, bool useEHCleanup);
  963. Destroyer &getDestroyer(QualType::DestructionKind destructionKind);
  964. /// Determines whether an EH cleanup is required to destroy a type
  965. /// with the given destruction kind.
  966. bool needsEHCleanup(QualType::DestructionKind kind) {
  967. switch (kind) {
  968. case QualType::DK_none:
  969. return false;
  970. case QualType::DK_cxx_destructor:
  971. case QualType::DK_objc_weak_lifetime:
  972. return getLangOptions().Exceptions;
  973. case QualType::DK_objc_strong_lifetime:
  974. return getLangOptions().Exceptions &&
  975. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  976. }
  977. llvm_unreachable("bad destruction kind");
  978. }
  979. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  980. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  981. }
  982. //===--------------------------------------------------------------------===//
  983. // Objective-C
  984. //===--------------------------------------------------------------------===//
  985. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  986. void StartObjCMethod(const ObjCMethodDecl *MD,
  987. const ObjCContainerDecl *CD,
  988. SourceLocation StartLoc);
  989. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  990. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  991. const ObjCPropertyImplDecl *PID);
  992. void GenerateObjCGetterBody(ObjCIvarDecl *Ivar, bool IsAtomic, bool IsStrong);
  993. void GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
  994. ObjCIvarDecl *Ivar);
  995. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  996. ObjCMethodDecl *MD, bool ctor);
  997. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  998. /// for the given property.
  999. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1000. const ObjCPropertyImplDecl *PID);
  1001. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  1002. bool IvarTypeWithAggrGCObjects(QualType Ty);
  1003. //===--------------------------------------------------------------------===//
  1004. // Block Bits
  1005. //===--------------------------------------------------------------------===//
  1006. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1007. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  1008. const CGBlockInfo &Info,
  1009. llvm::StructType *,
  1010. llvm::Constant *BlockVarLayout);
  1011. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1012. const CGBlockInfo &Info,
  1013. const Decl *OuterFuncDecl,
  1014. const DeclMapTy &ldm);
  1015. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1016. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1017. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1018. class AutoVarEmission;
  1019. void emitByrefStructureInit(const AutoVarEmission &emission);
  1020. void enterByrefCleanup(const AutoVarEmission &emission);
  1021. llvm::Value *LoadBlockStruct() {
  1022. assert(BlockPointer && "no block pointer set!");
  1023. return BlockPointer;
  1024. }
  1025. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  1026. void AllocateBlockDecl(const BlockDeclRefExpr *E);
  1027. llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
  1028. return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
  1029. }
  1030. llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1031. llvm::Type *BuildByRefType(const VarDecl *var);
  1032. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1033. const CGFunctionInfo &FnInfo);
  1034. void StartFunction(GlobalDecl GD, QualType RetTy,
  1035. llvm::Function *Fn,
  1036. const CGFunctionInfo &FnInfo,
  1037. const FunctionArgList &Args,
  1038. SourceLocation StartLoc);
  1039. void EmitConstructorBody(FunctionArgList &Args);
  1040. void EmitDestructorBody(FunctionArgList &Args);
  1041. void EmitFunctionBody(FunctionArgList &Args);
  1042. /// EmitReturnBlock - Emit the unified return block, trying to avoid its
  1043. /// emission when possible.
  1044. void EmitReturnBlock();
  1045. /// FinishFunction - Complete IR generation of the current function. It is
  1046. /// legal to call this function even if there is no current insertion point.
  1047. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1048. /// GenerateThunk - Generate a thunk for the given method.
  1049. void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1050. GlobalDecl GD, const ThunkInfo &Thunk);
  1051. void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1052. GlobalDecl GD, const ThunkInfo &Thunk);
  1053. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1054. FunctionArgList &Args);
  1055. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  1056. /// subobject.
  1057. ///
  1058. void InitializeVTablePointer(BaseSubobject Base,
  1059. const CXXRecordDecl *NearestVBase,
  1060. CharUnits OffsetFromNearestVBase,
  1061. llvm::Constant *VTable,
  1062. const CXXRecordDecl *VTableClass);
  1063. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1064. void InitializeVTablePointers(BaseSubobject Base,
  1065. const CXXRecordDecl *NearestVBase,
  1066. CharUnits OffsetFromNearestVBase,
  1067. bool BaseIsNonVirtualPrimaryBase,
  1068. llvm::Constant *VTable,
  1069. const CXXRecordDecl *VTableClass,
  1070. VisitedVirtualBasesSetTy& VBases);
  1071. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1072. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1073. /// to by This.
  1074. llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
  1075. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1076. /// given phase of destruction for a destructor. The end result
  1077. /// should call destructors on members and base classes in reverse
  1078. /// order of their construction.
  1079. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1080. /// ShouldInstrumentFunction - Return true if the current function should be
  1081. /// instrumented with __cyg_profile_func_* calls
  1082. bool ShouldInstrumentFunction();
  1083. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1084. /// instrumentation function with the current function and the call site, if
  1085. /// function instrumentation is enabled.
  1086. void EmitFunctionInstrumentation(const char *Fn);
  1087. /// EmitMCountInstrumentation - Emit call to .mcount.
  1088. void EmitMCountInstrumentation();
  1089. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1090. /// arguments for the given function. This is also responsible for naming the
  1091. /// LLVM function arguments.
  1092. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1093. llvm::Function *Fn,
  1094. const FunctionArgList &Args);
  1095. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1096. /// given temporary.
  1097. void EmitFunctionEpilog(const CGFunctionInfo &FI);
  1098. /// EmitStartEHSpec - Emit the start of the exception spec.
  1099. void EmitStartEHSpec(const Decl *D);
  1100. /// EmitEndEHSpec - Emit the end of the exception spec.
  1101. void EmitEndEHSpec(const Decl *D);
  1102. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1103. llvm::BasicBlock *getTerminateLandingPad();
  1104. /// getTerminateHandler - Return a handler (not a landing pad, just
  1105. /// a catch handler) that just calls terminate. This is used when
  1106. /// a terminate scope encloses a try.
  1107. llvm::BasicBlock *getTerminateHandler();
  1108. llvm::Type *ConvertTypeForMem(QualType T);
  1109. llvm::Type *ConvertType(QualType T);
  1110. llvm::Type *ConvertType(const TypeDecl *T) {
  1111. return ConvertType(getContext().getTypeDeclType(T));
  1112. }
  1113. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1114. /// generating code for an Objective-C method.
  1115. llvm::Value *LoadObjCSelf();
  1116. /// TypeOfSelfObject - Return type of object that this self represents.
  1117. QualType TypeOfSelfObject();
  1118. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1119. /// an aggregate LLVM type or is void.
  1120. static bool hasAggregateLLVMType(QualType T);
  1121. /// createBasicBlock - Create an LLVM basic block.
  1122. llvm::BasicBlock *createBasicBlock(StringRef name = "",
  1123. llvm::Function *parent = 0,
  1124. llvm::BasicBlock *before = 0) {
  1125. #ifdef NDEBUG
  1126. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1127. #else
  1128. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1129. #endif
  1130. }
  1131. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1132. /// label maps to.
  1133. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1134. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1135. /// another basic block, simplify it. This assumes that no other code could
  1136. /// potentially reference the basic block.
  1137. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1138. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1139. /// adding a fall-through branch from the current insert block if
  1140. /// necessary. It is legal to call this function even if there is no current
  1141. /// insertion point.
  1142. ///
  1143. /// IsFinished - If true, indicates that the caller has finished emitting
  1144. /// branches to the given block and does not expect to emit code into it. This
  1145. /// means the block can be ignored if it is unreachable.
  1146. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1147. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1148. /// near its uses, and leave the insertion point in it.
  1149. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1150. /// EmitBranch - Emit a branch to the specified basic block from the current
  1151. /// insert block, taking care to avoid creation of branches from dummy
  1152. /// blocks. It is legal to call this function even if there is no current
  1153. /// insertion point.
  1154. ///
  1155. /// This function clears the current insertion point. The caller should follow
  1156. /// calls to this function with calls to Emit*Block prior to generation new
  1157. /// code.
  1158. void EmitBranch(llvm::BasicBlock *Block);
  1159. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1160. /// indicates that the current code being emitted is unreachable.
  1161. bool HaveInsertPoint() const {
  1162. return Builder.GetInsertBlock() != 0;
  1163. }
  1164. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1165. /// emitted IR has a place to go. Note that by definition, if this function
  1166. /// creates a block then that block is unreachable; callers may do better to
  1167. /// detect when no insertion point is defined and simply skip IR generation.
  1168. void EnsureInsertPoint() {
  1169. if (!HaveInsertPoint())
  1170. EmitBlock(createBasicBlock());
  1171. }
  1172. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1173. /// specified stmt yet.
  1174. void ErrorUnsupported(const Stmt *S, const char *Type,
  1175. bool OmitOnError=false);
  1176. //===--------------------------------------------------------------------===//
  1177. // Helpers
  1178. //===--------------------------------------------------------------------===//
  1179. LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) {
  1180. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1181. CGM.getTBAAInfo(T));
  1182. }
  1183. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1184. /// block. The caller is responsible for setting an appropriate alignment on
  1185. /// the alloca.
  1186. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1187. const Twine &Name = "tmp");
  1188. /// InitTempAlloca - Provide an initial value for the given alloca.
  1189. void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
  1190. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1191. /// appropriate alignment. This routine should only be used when an temporary
  1192. /// value needs to be stored into an alloca (for example, to avoid explicit
  1193. /// PHI construction), but the type is the IR type, not the type appropriate
  1194. /// for storing in memory.
  1195. llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1196. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1197. /// appropriate alignment.
  1198. llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1199. /// CreateAggTemp - Create a temporary memory object for the given
  1200. /// aggregate type.
  1201. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1202. return AggValueSlot::forAddr(CreateMemTemp(T, Name), T.getQualifiers(),
  1203. AggValueSlot::IsNotDestructed,
  1204. AggValueSlot::DoesNotNeedGCBarriers,
  1205. AggValueSlot::IsNotAliased);
  1206. }
  1207. /// Emit a cast to void* in the appropriate address space.
  1208. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1209. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1210. /// expression and compare the result against zero, returning an Int1Ty value.
  1211. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1212. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1213. void EmitIgnoredExpr(const Expr *E);
  1214. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1215. /// any type. The result is returned as an RValue struct. If this is an
  1216. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1217. /// the result should be returned.
  1218. ///
  1219. /// \param IgnoreResult - True if the resulting value isn't used.
  1220. RValue EmitAnyExpr(const Expr *E,
  1221. AggValueSlot AggSlot = AggValueSlot::ignored(),
  1222. bool IgnoreResult = false);
  1223. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1224. // or the value of the expression, depending on how va_list is defined.
  1225. llvm::Value *EmitVAListRef(const Expr *E);
  1226. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1227. /// always be accessible even if no aggregate location is provided.
  1228. RValue EmitAnyExprToTemp(const Expr *E);
  1229. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1230. /// arbitrary expression into the given memory location.
  1231. void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
  1232. Qualifiers Quals, bool IsInitializer);
  1233. /// EmitExprAsInit - Emits the code necessary to initialize a
  1234. /// location in memory with the given initializer.
  1235. void EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1236. LValue lvalue, bool capturedByInit);
  1237. /// EmitAggregateCopy - Emit an aggrate copy.
  1238. ///
  1239. /// \param isVolatile - True iff either the source or the destination is
  1240. /// volatile.
  1241. void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1242. QualType EltTy, bool isVolatile=false);
  1243. /// StartBlock - Start new block named N. If insert block is a dummy block
  1244. /// then reuse it.
  1245. void StartBlock(const char *N);
  1246. /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
  1247. llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
  1248. return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
  1249. }
  1250. /// GetAddrOfLocalVar - Return the address of a local variable.
  1251. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
  1252. llvm::Value *Res = LocalDeclMap[VD];
  1253. assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1254. return Res;
  1255. }
  1256. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1257. /// must be mapped to an l-value), return its mapping.
  1258. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1259. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1260. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1261. it = OpaqueLValues.find(e);
  1262. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1263. return it->second;
  1264. }
  1265. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1266. /// must be mapped to an r-value), return its mapping.
  1267. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1268. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1269. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1270. it = OpaqueRValues.find(e);
  1271. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1272. return it->second;
  1273. }
  1274. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1275. /// the input field number being accessed.
  1276. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1277. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1278. llvm::BasicBlock *GetIndirectGotoBlock();
  1279. /// EmitNullInitialization - Generate code to set a value of the given type to
  1280. /// null, If the type contains data member pointers, they will be initialized
  1281. /// to -1 in accordance with the Itanium C++ ABI.
  1282. void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
  1283. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1284. // and update it accordingly. The return value is a pointer to the argument.
  1285. // FIXME: We should be able to get rid of this method and use the va_arg
  1286. // instruction in LLVM instead once it works well enough.
  1287. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
  1288. /// emitArrayLength - Compute the length of an array, even if it's a
  1289. /// VLA, and drill down to the base element type.
  1290. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1291. QualType &baseType,
  1292. llvm::Value *&addr);
  1293. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1294. /// the given variably-modified type and store them in the VLASizeMap.
  1295. ///
  1296. /// This function can be called with a null (unreachable) insert point.
  1297. void EmitVariablyModifiedType(QualType Ty);
  1298. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1299. /// in non-variably-sized elements, of a variable length array type,
  1300. /// plus that largest non-variably-sized element type. Assumes that
  1301. /// the type has already been emitted with EmitVariablyModifiedType.
  1302. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1303. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1304. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1305. /// generating code for an C++ member function.
  1306. llvm::Value *LoadCXXThis() {
  1307. assert(CXXThisValue && "no 'this' value for this function");
  1308. return CXXThisValue;
  1309. }
  1310. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1311. /// virtual bases.
  1312. llvm::Value *LoadCXXVTT() {
  1313. assert(CXXVTTValue && "no VTT value for this function");
  1314. return CXXVTTValue;
  1315. }
  1316. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1317. /// complete class to the given direct base.
  1318. llvm::Value *
  1319. GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
  1320. const CXXRecordDecl *Derived,
  1321. const CXXRecordDecl *Base,
  1322. bool BaseIsVirtual);
  1323. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1324. /// load of 'this' and returns address of the base class.
  1325. llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
  1326. const CXXRecordDecl *Derived,
  1327. CastExpr::path_const_iterator PathBegin,
  1328. CastExpr::path_const_iterator PathEnd,
  1329. bool NullCheckValue);
  1330. llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
  1331. const CXXRecordDecl *Derived,
  1332. CastExpr::path_const_iterator PathBegin,
  1333. CastExpr::path_const_iterator PathEnd,
  1334. bool NullCheckValue);
  1335. llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
  1336. const CXXRecordDecl *ClassDecl,
  1337. const CXXRecordDecl *BaseClassDecl);
  1338. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1339. CXXCtorType CtorType,
  1340. const FunctionArgList &Args);
  1341. // It's important not to confuse this and the previous function. Delegating
  1342. // constructors are the C++0x feature. The constructor delegate optimization
  1343. // is used to reduce duplication in the base and complete consturctors where
  1344. // they are substantially the same.
  1345. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1346. const FunctionArgList &Args);
  1347. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1348. bool ForVirtualBase, llvm::Value *This,
  1349. CallExpr::const_arg_iterator ArgBeg,
  1350. CallExpr::const_arg_iterator ArgEnd);
  1351. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1352. llvm::Value *This, llvm::Value *Src,
  1353. CallExpr::const_arg_iterator ArgBeg,
  1354. CallExpr::const_arg_iterator ArgEnd);
  1355. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1356. const ConstantArrayType *ArrayTy,
  1357. llvm::Value *ArrayPtr,
  1358. CallExpr::const_arg_iterator ArgBeg,
  1359. CallExpr::const_arg_iterator ArgEnd,
  1360. bool ZeroInitialization = false);
  1361. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1362. llvm::Value *NumElements,
  1363. llvm::Value *ArrayPtr,
  1364. CallExpr::const_arg_iterator ArgBeg,
  1365. CallExpr::const_arg_iterator ArgEnd,
  1366. bool ZeroInitialization = false);
  1367. static Destroyer destroyCXXObject;
  1368. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1369. bool ForVirtualBase, llvm::Value *This);
  1370. void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
  1371. llvm::Value *NumElements);
  1372. void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
  1373. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1374. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1375. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1376. QualType DeleteTy);
  1377. llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1378. llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
  1379. void EmitCheck(llvm::Value *, unsigned Size);
  1380. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1381. bool isInc, bool isPre);
  1382. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1383. bool isInc, bool isPre);
  1384. //===--------------------------------------------------------------------===//
  1385. // Declaration Emission
  1386. //===--------------------------------------------------------------------===//
  1387. /// EmitDecl - Emit a declaration.
  1388. ///
  1389. /// This function can be called with a null (unreachable) insert point.
  1390. void EmitDecl(const Decl &D);
  1391. /// EmitVarDecl - Emit a local variable declaration.
  1392. ///
  1393. /// This function can be called with a null (unreachable) insert point.
  1394. void EmitVarDecl(const VarDecl &D);
  1395. void EmitScalarInit(const Expr *init, const ValueDecl *D,
  1396. LValue lvalue, bool capturedByInit);
  1397. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1398. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1399. llvm::Value *Address);
  1400. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1401. ///
  1402. /// This function can be called with a null (unreachable) insert point.
  1403. void EmitAutoVarDecl(const VarDecl &D);
  1404. class AutoVarEmission {
  1405. friend class CodeGenFunction;
  1406. const VarDecl *Variable;
  1407. /// The alignment of the variable.
  1408. CharUnits Alignment;
  1409. /// The address of the alloca. Null if the variable was emitted
  1410. /// as a global constant.
  1411. llvm::Value *Address;
  1412. llvm::Value *NRVOFlag;
  1413. /// True if the variable is a __block variable.
  1414. bool IsByRef;
  1415. /// True if the variable is of aggregate type and has a constant
  1416. /// initializer.
  1417. bool IsConstantAggregate;
  1418. struct Invalid {};
  1419. AutoVarEmission(Invalid) : Variable(0) {}
  1420. AutoVarEmission(const VarDecl &variable)
  1421. : Variable(&variable), Address(0), NRVOFlag(0),
  1422. IsByRef(false), IsConstantAggregate(false) {}
  1423. bool wasEmittedAsGlobal() const { return Address == 0; }
  1424. public:
  1425. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1426. /// Returns the address of the object within this declaration.
  1427. /// Note that this does not chase the forwarding pointer for
  1428. /// __block decls.
  1429. llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
  1430. if (!IsByRef) return Address;
  1431. return CGF.Builder.CreateStructGEP(Address,
  1432. CGF.getByRefValueLLVMField(Variable),
  1433. Variable->getNameAsString());
  1434. }
  1435. };
  1436. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1437. void EmitAutoVarInit(const AutoVarEmission &emission);
  1438. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1439. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1440. QualType::DestructionKind dtorKind);
  1441. void EmitStaticVarDecl(const VarDecl &D,
  1442. llvm::GlobalValue::LinkageTypes Linkage);
  1443. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1444. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
  1445. /// protectFromPeepholes - Protect a value that we're intending to
  1446. /// store to the side, but which will probably be used later, from
  1447. /// aggressive peepholing optimizations that might delete it.
  1448. ///
  1449. /// Pass the result to unprotectFromPeepholes to declare that
  1450. /// protection is no longer required.
  1451. ///
  1452. /// There's no particular reason why this shouldn't apply to
  1453. /// l-values, it's just that no existing peepholes work on pointers.
  1454. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1455. void unprotectFromPeepholes(PeepholeProtection protection);
  1456. //===--------------------------------------------------------------------===//
  1457. // Statement Emission
  1458. //===--------------------------------------------------------------------===//
  1459. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1460. void EmitStopPoint(const Stmt *S);
  1461. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1462. /// this function even if there is no current insertion point.
  1463. ///
  1464. /// This function may clear the current insertion point; callers should use
  1465. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1466. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1467. void EmitStmt(const Stmt *S);
  1468. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1469. /// necessarily require an insertion point or debug information; typically
  1470. /// because the statement amounts to a jump or a container of other
  1471. /// statements.
  1472. ///
  1473. /// \return True if the statement was handled.
  1474. bool EmitSimpleStmt(const Stmt *S);
  1475. RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1476. AggValueSlot AVS = AggValueSlot::ignored());
  1477. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1478. /// function even if there is no current insertion point.
  1479. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1480. void EmitLabelStmt(const LabelStmt &S);
  1481. void EmitGotoStmt(const GotoStmt &S);
  1482. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1483. void EmitIfStmt(const IfStmt &S);
  1484. void EmitWhileStmt(const WhileStmt &S);
  1485. void EmitDoStmt(const DoStmt &S);
  1486. void EmitForStmt(const ForStmt &S);
  1487. void EmitReturnStmt(const ReturnStmt &S);
  1488. void EmitDeclStmt(const DeclStmt &S);
  1489. void EmitBreakStmt(const BreakStmt &S);
  1490. void EmitContinueStmt(const ContinueStmt &S);
  1491. void EmitSwitchStmt(const SwitchStmt &S);
  1492. void EmitDefaultStmt(const DefaultStmt &S);
  1493. void EmitCaseStmt(const CaseStmt &S);
  1494. void EmitCaseStmtRange(const CaseStmt &S);
  1495. void EmitAsmStmt(const AsmStmt &S);
  1496. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1497. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1498. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1499. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1500. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1501. llvm::Constant *getUnwindResumeFn();
  1502. llvm::Constant *getUnwindResumeOrRethrowFn();
  1503. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1504. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1505. void EmitCXXTryStmt(const CXXTryStmt &S);
  1506. void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
  1507. //===--------------------------------------------------------------------===//
  1508. // LValue Expression Emission
  1509. //===--------------------------------------------------------------------===//
  1510. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1511. RValue GetUndefRValue(QualType Ty);
  1512. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1513. /// and issue an ErrorUnsupported style diagnostic (using the
  1514. /// provided Name).
  1515. RValue EmitUnsupportedRValue(const Expr *E,
  1516. const char *Name);
  1517. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1518. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1519. LValue EmitUnsupportedLValue(const Expr *E,
  1520. const char *Name);
  1521. /// EmitLValue - Emit code to compute a designator that specifies the location
  1522. /// of the expression.
  1523. ///
  1524. /// This can return one of two things: a simple address or a bitfield
  1525. /// reference. In either case, the LLVM Value* in the LValue structure is
  1526. /// guaranteed to be an LLVM pointer type.
  1527. ///
  1528. /// If this returns a bitfield reference, nothing about the pointee type of
  1529. /// the LLVM value is known: For example, it may not be a pointer to an
  1530. /// integer.
  1531. ///
  1532. /// If this returns a normal address, and if the lvalue's C type is fixed
  1533. /// size, this method guarantees that the returned pointer type will point to
  1534. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  1535. /// variable length type, this is not possible.
  1536. ///
  1537. LValue EmitLValue(const Expr *E);
  1538. /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
  1539. /// checking code to guard against undefined behavior. This is only
  1540. /// suitable when we know that the address will be used to access the
  1541. /// object.
  1542. LValue EmitCheckedLValue(const Expr *E);
  1543. /// EmitToMemory - Change a scalar value from its value
  1544. /// representation to its in-memory representation.
  1545. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  1546. /// EmitFromMemory - Change a scalar value from its memory
  1547. /// representation to its value representation.
  1548. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  1549. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1550. /// care to appropriately convert from the memory representation to
  1551. /// the LLVM value representation.
  1552. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1553. unsigned Alignment, QualType Ty,
  1554. llvm::MDNode *TBAAInfo = 0);
  1555. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1556. /// care to appropriately convert from the memory representation to
  1557. /// the LLVM value representation. The l-value must be a simple
  1558. /// l-value.
  1559. llvm::Value *EmitLoadOfScalar(LValue lvalue);
  1560. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1561. /// care to appropriately convert from the memory representation to
  1562. /// the LLVM value representation.
  1563. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1564. bool Volatile, unsigned Alignment, QualType Ty,
  1565. llvm::MDNode *TBAAInfo = 0);
  1566. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1567. /// care to appropriately convert from the memory representation to
  1568. /// the LLVM value representation. The l-value must be a simple
  1569. /// l-value.
  1570. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue);
  1571. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  1572. /// this method emits the address of the lvalue, then loads the result as an
  1573. /// rvalue, returning the rvalue.
  1574. RValue EmitLoadOfLValue(LValue V);
  1575. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  1576. RValue EmitLoadOfBitfieldLValue(LValue LV);
  1577. RValue EmitLoadOfPropertyRefLValue(LValue LV,
  1578. ReturnValueSlot Return = ReturnValueSlot());
  1579. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1580. /// lvalue, where both are guaranteed to the have the same type, and that type
  1581. /// is 'Ty'.
  1582. void EmitStoreThroughLValue(RValue Src, LValue Dst);
  1583. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  1584. void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst);
  1585. /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
  1586. /// EmitStoreThroughLValue.
  1587. ///
  1588. /// \param Result [out] - If non-null, this will be set to a Value* for the
  1589. /// bit-field contents after the store, appropriate for use as the result of
  1590. /// an assignment to the bit-field.
  1591. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1592. llvm::Value **Result=0);
  1593. /// Emit an l-value for an assignment (simple or compound) of complex type.
  1594. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  1595. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1596. // Note: only available for agg return types
  1597. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  1598. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1599. // Note: only available for agg return types
  1600. LValue EmitCallExprLValue(const CallExpr *E);
  1601. // Note: only available for agg return types
  1602. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  1603. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  1604. LValue EmitStringLiteralLValue(const StringLiteral *E);
  1605. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  1606. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  1607. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  1608. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
  1609. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  1610. LValue EmitMemberExpr(const MemberExpr *E);
  1611. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  1612. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  1613. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  1614. LValue EmitCastLValue(const CastExpr *E);
  1615. LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
  1616. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  1617. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  1618. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  1619. const ObjCIvarDecl *Ivar);
  1620. LValue EmitLValueForAnonRecordField(llvm::Value* Base,
  1621. const IndirectFieldDecl* Field,
  1622. unsigned CVRQualifiers);
  1623. LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
  1624. unsigned CVRQualifiers);
  1625. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  1626. /// if the Field is a reference, this will return the address of the reference
  1627. /// and not the address of the value stored in the reference.
  1628. LValue EmitLValueForFieldInitialization(llvm::Value* Base,
  1629. const FieldDecl* Field,
  1630. unsigned CVRQualifiers);
  1631. LValue EmitLValueForIvar(QualType ObjectTy,
  1632. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  1633. unsigned CVRQualifiers);
  1634. LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
  1635. unsigned CVRQualifiers);
  1636. LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
  1637. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  1638. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  1639. LValue EmitExprWithCleanupsLValue(const ExprWithCleanups *E);
  1640. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  1641. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  1642. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  1643. LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
  1644. LValue EmitStmtExprLValue(const StmtExpr *E);
  1645. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  1646. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  1647. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  1648. //===--------------------------------------------------------------------===//
  1649. // Scalar Expression Emission
  1650. //===--------------------------------------------------------------------===//
  1651. /// EmitCall - Generate a call of the given function, expecting the given
  1652. /// result type, and using the given argument list which specifies both the
  1653. /// LLVM arguments and the types they were derived from.
  1654. ///
  1655. /// \param TargetDecl - If given, the decl of the function in a direct call;
  1656. /// used to set attributes on the call (noreturn, etc.).
  1657. RValue EmitCall(const CGFunctionInfo &FnInfo,
  1658. llvm::Value *Callee,
  1659. ReturnValueSlot ReturnValue,
  1660. const CallArgList &Args,
  1661. const Decl *TargetDecl = 0,
  1662. llvm::Instruction **callOrInvoke = 0);
  1663. RValue EmitCall(QualType FnType, llvm::Value *Callee,
  1664. ReturnValueSlot ReturnValue,
  1665. CallExpr::const_arg_iterator ArgBeg,
  1666. CallExpr::const_arg_iterator ArgEnd,
  1667. const Decl *TargetDecl = 0);
  1668. RValue EmitCallExpr(const CallExpr *E,
  1669. ReturnValueSlot ReturnValue = ReturnValueSlot());
  1670. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1671. ArrayRef<llvm::Value *> Args,
  1672. const Twine &Name = "");
  1673. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1674. const Twine &Name = "");
  1675. llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
  1676. llvm::Type *Ty);
  1677. llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
  1678. llvm::Value *This, llvm::Type *Ty);
  1679. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  1680. NestedNameSpecifier *Qual,
  1681. llvm::Type *Ty);
  1682. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  1683. CXXDtorType Type,
  1684. const CXXRecordDecl *RD);
  1685. RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
  1686. llvm::Value *Callee,
  1687. ReturnValueSlot ReturnValue,
  1688. llvm::Value *This,
  1689. llvm::Value *VTT,
  1690. CallExpr::const_arg_iterator ArgBeg,
  1691. CallExpr::const_arg_iterator ArgEnd);
  1692. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  1693. ReturnValueSlot ReturnValue);
  1694. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  1695. ReturnValueSlot ReturnValue);
  1696. llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1697. const CXXMethodDecl *MD,
  1698. llvm::Value *This);
  1699. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  1700. const CXXMethodDecl *MD,
  1701. ReturnValueSlot ReturnValue);
  1702. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  1703. unsigned BuiltinID, const CallExpr *E);
  1704. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  1705. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  1706. /// is unhandled by the current target.
  1707. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1708. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1709. llvm::Value *EmitNeonCall(llvm::Function *F,
  1710. SmallVectorImpl<llvm::Value*> &O,
  1711. const char *name,
  1712. unsigned shift = 0, bool rightshift = false);
  1713. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  1714. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  1715. bool negateForRightShift);
  1716. llvm::Value *BuildVector(const SmallVectorImpl<llvm::Value*> &Ops);
  1717. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1718. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1719. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  1720. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  1721. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  1722. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  1723. ReturnValueSlot Return = ReturnValueSlot());
  1724. /// Retrieves the default cleanup kind for an ARC cleanup.
  1725. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  1726. CleanupKind getARCCleanupKind() {
  1727. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  1728. ? NormalAndEHCleanup : NormalCleanup;
  1729. }
  1730. // ARC primitives.
  1731. void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
  1732. void EmitARCDestroyWeak(llvm::Value *addr);
  1733. llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
  1734. llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
  1735. llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
  1736. bool ignored);
  1737. void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
  1738. void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
  1739. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  1740. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  1741. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  1742. bool ignored);
  1743. llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
  1744. bool ignored);
  1745. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  1746. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  1747. llvm::Value *EmitARCRetainBlock(llvm::Value *value);
  1748. void EmitARCRelease(llvm::Value *value, bool precise);
  1749. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  1750. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  1751. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  1752. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  1753. std::pair<LValue,llvm::Value*>
  1754. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  1755. std::pair<LValue,llvm::Value*>
  1756. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  1757. llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
  1758. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  1759. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  1760. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  1761. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  1762. static Destroyer destroyARCStrongImprecise;
  1763. static Destroyer destroyARCStrongPrecise;
  1764. static Destroyer destroyARCWeak;
  1765. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  1766. llvm::Value *EmitObjCAutoreleasePoolPush();
  1767. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  1768. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  1769. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  1770. /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
  1771. /// expression. Will emit a temporary variable if E is not an LValue.
  1772. RValue EmitReferenceBindingToExpr(const Expr* E,
  1773. const NamedDecl *InitializedDecl);
  1774. //===--------------------------------------------------------------------===//
  1775. // Expression Emission
  1776. //===--------------------------------------------------------------------===//
  1777. // Expressions are broken into three classes: scalar, complex, aggregate.
  1778. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  1779. /// scalar type, returning the result.
  1780. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  1781. /// EmitScalarConversion - Emit a conversion from the specified type to the
  1782. /// specified destination type, both of which are LLVM scalar types.
  1783. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  1784. QualType DstTy);
  1785. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  1786. /// complex type to the specified destination type, where the destination type
  1787. /// is an LLVM scalar type.
  1788. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  1789. QualType DstTy);
  1790. /// EmitAggExpr - Emit the computation of the specified expression
  1791. /// of aggregate type. The result is computed into the given slot,
  1792. /// which may be null to indicate that the value is not needed.
  1793. void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false);
  1794. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  1795. /// aggregate type into a temporary LValue.
  1796. LValue EmitAggExprToLValue(const Expr *E);
  1797. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  1798. /// pointers.
  1799. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1800. QualType Ty);
  1801. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  1802. /// make sure it survives garbage collection until this point.
  1803. void EmitExtendGCLifetime(llvm::Value *object);
  1804. /// EmitComplexExpr - Emit the computation of the specified expression of
  1805. /// complex type, returning the result.
  1806. ComplexPairTy EmitComplexExpr(const Expr *E,
  1807. bool IgnoreReal = false,
  1808. bool IgnoreImag = false);
  1809. /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
  1810. /// of complex type, storing into the specified Value*.
  1811. void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
  1812. bool DestIsVolatile);
  1813. /// StoreComplexToAddr - Store a complex number into the specified address.
  1814. void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
  1815. bool DestIsVolatile);
  1816. /// LoadComplexFromAddr - Load a complex number from the specified address.
  1817. ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
  1818. /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
  1819. /// a static local variable.
  1820. llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
  1821. const char *Separator,
  1822. llvm::GlobalValue::LinkageTypes Linkage);
  1823. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  1824. /// global variable that has already been created for it. If the initializer
  1825. /// has a different type than GV does, this may free GV and return a different
  1826. /// one. Otherwise it just returns GV.
  1827. llvm::GlobalVariable *
  1828. AddInitializerToStaticVarDecl(const VarDecl &D,
  1829. llvm::GlobalVariable *GV);
  1830. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  1831. /// variable with global storage.
  1832. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
  1833. /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
  1834. /// with the C++ runtime so that its destructor will be called at exit.
  1835. void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
  1836. llvm::Constant *DeclPtr);
  1837. /// Emit code in this function to perform a guarded variable
  1838. /// initialization. Guarded initializations are used when it's not
  1839. /// possible to prove that an initialization will be done exactly
  1840. /// once, e.g. with a static local variable or a static data member
  1841. /// of a class template.
  1842. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr);
  1843. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  1844. /// variables.
  1845. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  1846. llvm::Constant **Decls,
  1847. unsigned NumDecls);
  1848. /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
  1849. /// variables.
  1850. void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
  1851. const std::vector<std::pair<llvm::WeakVH,
  1852. llvm::Constant*> > &DtorsAndObjects);
  1853. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  1854. const VarDecl *D,
  1855. llvm::GlobalVariable *Addr);
  1856. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  1857. void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
  1858. const Expr *Exp);
  1859. RValue EmitExprWithCleanups(const ExprWithCleanups *E,
  1860. AggValueSlot Slot =AggValueSlot::ignored());
  1861. void EmitCXXThrowExpr(const CXXThrowExpr *E);
  1862. //===--------------------------------------------------------------------===//
  1863. // Internal Helpers
  1864. //===--------------------------------------------------------------------===//
  1865. /// ContainsLabel - Return true if the statement contains a label in it. If
  1866. /// this statement is not executed normally, it not containing a label means
  1867. /// that we can just remove the code.
  1868. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  1869. /// containsBreak - Return true if the statement contains a break out of it.
  1870. /// If the statement (recursively) contains a switch or loop with a break
  1871. /// inside of it, this is fine.
  1872. static bool containsBreak(const Stmt *S);
  1873. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1874. /// to a constant, or if it does but contains a label, return false. If it
  1875. /// constant folds return true and set the boolean result in Result.
  1876. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  1877. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1878. /// to a constant, or if it does but contains a label, return false. If it
  1879. /// constant folds return true and set the folded value.
  1880. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &Result);
  1881. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  1882. /// if statement) to the specified blocks. Based on the condition, this might
  1883. /// try to simplify the codegen of the conditional based on the branch.
  1884. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  1885. llvm::BasicBlock *FalseBlock);
  1886. /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll
  1887. /// generate a branch around the created basic block as necessary.
  1888. llvm::BasicBlock *getTrapBB();
  1889. /// EmitCallArg - Emit a single call argument.
  1890. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  1891. /// EmitDelegateCallArg - We are performing a delegate call; that
  1892. /// is, the current function is delegating to another one. Produce
  1893. /// a r-value suitable for passing the given parameter.
  1894. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param);
  1895. private:
  1896. void EmitReturnOfRValue(RValue RV, QualType Ty);
  1897. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  1898. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  1899. ///
  1900. /// \param AI - The first function argument of the expansion.
  1901. /// \return The argument following the last expanded function
  1902. /// argument.
  1903. llvm::Function::arg_iterator
  1904. ExpandTypeFromArgs(QualType Ty, LValue Dst,
  1905. llvm::Function::arg_iterator AI);
  1906. /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
  1907. /// Ty, into individual arguments on the provided vector \arg Args. See
  1908. /// ABIArgInfo::Expand.
  1909. void ExpandTypeToArgs(QualType Ty, RValue Src,
  1910. SmallVector<llvm::Value*, 16> &Args,
  1911. llvm::FunctionType *IRFuncTy);
  1912. llvm::Value* EmitAsmInput(const AsmStmt &S,
  1913. const TargetInfo::ConstraintInfo &Info,
  1914. const Expr *InputExpr, std::string &ConstraintStr);
  1915. llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
  1916. const TargetInfo::ConstraintInfo &Info,
  1917. LValue InputValue, QualType InputType,
  1918. std::string &ConstraintStr);
  1919. /// EmitCallArgs - Emit call arguments for a function.
  1920. /// The CallArgTypeInfo parameter is used for iterating over the known
  1921. /// argument types of the function being called.
  1922. template<typename T>
  1923. void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
  1924. CallExpr::const_arg_iterator ArgBeg,
  1925. CallExpr::const_arg_iterator ArgEnd) {
  1926. CallExpr::const_arg_iterator Arg = ArgBeg;
  1927. // First, use the argument types that the type info knows about
  1928. if (CallArgTypeInfo) {
  1929. for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
  1930. E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
  1931. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1932. QualType ArgType = *I;
  1933. #ifndef NDEBUG
  1934. QualType ActualArgType = Arg->getType();
  1935. if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
  1936. QualType ActualBaseType =
  1937. ActualArgType->getAs<PointerType>()->getPointeeType();
  1938. QualType ArgBaseType =
  1939. ArgType->getAs<PointerType>()->getPointeeType();
  1940. if (ArgBaseType->isVariableArrayType()) {
  1941. if (const VariableArrayType *VAT =
  1942. getContext().getAsVariableArrayType(ActualBaseType)) {
  1943. if (!VAT->getSizeExpr())
  1944. ActualArgType = ArgType;
  1945. }
  1946. }
  1947. }
  1948. assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
  1949. getTypePtr() ==
  1950. getContext().getCanonicalType(ActualArgType).getTypePtr() &&
  1951. "type mismatch in call argument!");
  1952. #endif
  1953. EmitCallArg(Args, *Arg, ArgType);
  1954. }
  1955. // Either we've emitted all the call args, or we have a call to a
  1956. // variadic function.
  1957. assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
  1958. "Extra arguments in non-variadic function!");
  1959. }
  1960. // If we still have any arguments, emit them using the type of the argument.
  1961. for (; Arg != ArgEnd; ++Arg)
  1962. EmitCallArg(Args, *Arg, Arg->getType());
  1963. }
  1964. const TargetCodeGenInfo &getTargetHooks() const {
  1965. return CGM.getTargetCodeGenInfo();
  1966. }
  1967. void EmitDeclMetadata();
  1968. CodeGenModule::ByrefHelpers *
  1969. buildByrefHelpers(llvm::StructType &byrefType,
  1970. const AutoVarEmission &emission);
  1971. };
  1972. /// Helper class with most of the code for saving a value for a
  1973. /// conditional expression cleanup.
  1974. struct DominatingLLVMValue {
  1975. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  1976. /// Answer whether the given value needs extra work to be saved.
  1977. static bool needsSaving(llvm::Value *value) {
  1978. // If it's not an instruction, we don't need to save.
  1979. if (!isa<llvm::Instruction>(value)) return false;
  1980. // If it's an instruction in the entry block, we don't need to save.
  1981. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  1982. return (block != &block->getParent()->getEntryBlock());
  1983. }
  1984. /// Try to save the given value.
  1985. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  1986. if (!needsSaving(value)) return saved_type(value, false);
  1987. // Otherwise we need an alloca.
  1988. llvm::Value *alloca =
  1989. CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
  1990. CGF.Builder.CreateStore(value, alloca);
  1991. return saved_type(alloca, true);
  1992. }
  1993. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  1994. if (!value.getInt()) return value.getPointer();
  1995. return CGF.Builder.CreateLoad(value.getPointer());
  1996. }
  1997. };
  1998. /// A partial specialization of DominatingValue for llvm::Values that
  1999. /// might be llvm::Instructions.
  2000. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2001. typedef T *type;
  2002. static type restore(CodeGenFunction &CGF, saved_type value) {
  2003. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2004. }
  2005. };
  2006. /// A specialization of DominatingValue for RValue.
  2007. template <> struct DominatingValue<RValue> {
  2008. typedef RValue type;
  2009. class saved_type {
  2010. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2011. AggregateAddress, ComplexAddress };
  2012. llvm::Value *Value;
  2013. Kind K;
  2014. saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
  2015. public:
  2016. static bool needsSaving(RValue value);
  2017. static saved_type save(CodeGenFunction &CGF, RValue value);
  2018. RValue restore(CodeGenFunction &CGF);
  2019. // implementations in CGExprCXX.cpp
  2020. };
  2021. static bool needsSaving(type value) {
  2022. return saved_type::needsSaving(value);
  2023. }
  2024. static saved_type save(CodeGenFunction &CGF, type value) {
  2025. return saved_type::save(CGF, value);
  2026. }
  2027. static type restore(CodeGenFunction &CGF, saved_type value) {
  2028. return value.restore(CGF);
  2029. }
  2030. };
  2031. } // end namespace CodeGen
  2032. } // end namespace clang
  2033. #endif