CodeGenFunction.h 109 KB

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