Implement the JIT side of the GDB JIT debugging interface. To enable this
[oota-llvm.git] / lib / ExecutionEngine / JIT / JITDwarfEmitter.cpp
1 //===----- JITDwarfEmitter.cpp - Write dwarf tables into memory -----------===//
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 file defines a JITDwarfEmitter object that is used by the JIT to
11 // write dwarf tables to memory.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "JIT.h"
16 #include "JITDwarfEmitter.h"
17 #include "llvm/Function.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/CodeGen/JITCodeEmitter.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineLocation.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/ExecutionEngine/JITMemoryManager.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 using namespace llvm;
32
33 JITDwarfEmitter::JITDwarfEmitter(JIT& theJit) : Jit(theJit) {}
34
35
36 unsigned char* JITDwarfEmitter::EmitDwarfTable(MachineFunction& F, 
37                                                JITCodeEmitter& jce,
38                                                unsigned char* StartFunction,
39                                                unsigned char* EndFunction,
40                                                unsigned char* &EHFramePtr) {
41   const TargetMachine& TM = F.getTarget();
42   TD = TM.getTargetData();
43   stackGrowthDirection = TM.getFrameInfo()->getStackGrowthDirection();
44   RI = TM.getRegisterInfo();
45   JCE = &jce;
46   
47   unsigned char* ExceptionTable = EmitExceptionTable(&F, StartFunction,
48                                                      EndFunction);
49       
50   unsigned char* Result = 0;
51
52   const std::vector<Function *> Personalities = MMI->getPersonalities();
53   EHFramePtr = EmitCommonEHFrame(Personalities[MMI->getPersonalityIndex()]);
54
55   Result = EmitEHFrame(Personalities[MMI->getPersonalityIndex()], EHFramePtr,
56                        StartFunction, EndFunction, ExceptionTable);
57
58   return Result;
59 }
60
61
62 void 
63 JITDwarfEmitter::EmitFrameMoves(intptr_t BaseLabelPtr,
64                                 const std::vector<MachineMove> &Moves) const {
65   unsigned PointerSize = TD->getPointerSize();
66   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
67           PointerSize : -PointerSize;
68   bool IsLocal = false;
69   unsigned BaseLabelID = 0;
70
71   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
72     const MachineMove &Move = Moves[i];
73     unsigned LabelID = Move.getLabelID();
74     
75     if (LabelID) {
76       LabelID = MMI->MappedLabel(LabelID);
77     
78       // Throw out move if the label is invalid.
79       if (!LabelID) continue;
80     }
81     
82     intptr_t LabelPtr = 0;
83     if (LabelID) LabelPtr = JCE->getLabelAddress(LabelID);
84
85     const MachineLocation &Dst = Move.getDestination();
86     const MachineLocation &Src = Move.getSource();
87     
88     // Advance row if new location.
89     if (BaseLabelPtr && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
90       JCE->emitByte(dwarf::DW_CFA_advance_loc4);
91       JCE->emitInt32(LabelPtr - BaseLabelPtr);
92       
93       BaseLabelID = LabelID; 
94       BaseLabelPtr = LabelPtr;
95       IsLocal = true;
96     }
97     
98     // If advancing cfa.
99     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
100       if (!Src.isReg()) {
101         if (Src.getReg() == MachineLocation::VirtualFP) {
102           JCE->emitByte(dwarf::DW_CFA_def_cfa_offset);
103         } else {
104           JCE->emitByte(dwarf::DW_CFA_def_cfa);
105           JCE->emitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), true));
106         }
107         
108         JCE->emitULEB128Bytes(-Src.getOffset());
109       } else {
110         llvm_unreachable("Machine move not supported yet.");
111       }
112     } else if (Src.isReg() &&
113       Src.getReg() == MachineLocation::VirtualFP) {
114       if (Dst.isReg()) {
115         JCE->emitByte(dwarf::DW_CFA_def_cfa_register);
116         JCE->emitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), true));
117       } else {
118         llvm_unreachable("Machine move not supported yet.");
119       }
120     } else {
121       unsigned Reg = RI->getDwarfRegNum(Src.getReg(), true);
122       int Offset = Dst.getOffset() / stackGrowth;
123       
124       if (Offset < 0) {
125         JCE->emitByte(dwarf::DW_CFA_offset_extended_sf);
126         JCE->emitULEB128Bytes(Reg);
127         JCE->emitSLEB128Bytes(Offset);
128       } else if (Reg < 64) {
129         JCE->emitByte(dwarf::DW_CFA_offset + Reg);
130         JCE->emitULEB128Bytes(Offset);
131       } else {
132         JCE->emitByte(dwarf::DW_CFA_offset_extended);
133         JCE->emitULEB128Bytes(Reg);
134         JCE->emitULEB128Bytes(Offset);
135       }
136     }
137   }
138 }
139
140 /// SharedTypeIds - How many leading type ids two landing pads have in common.
141 static unsigned SharedTypeIds(const LandingPadInfo *L,
142                               const LandingPadInfo *R) {
143   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
144   unsigned LSize = LIds.size(), RSize = RIds.size();
145   unsigned MinSize = LSize < RSize ? LSize : RSize;
146   unsigned Count = 0;
147
148   for (; Count != MinSize; ++Count)
149     if (LIds[Count] != RIds[Count])
150       return Count;
151
152   return Count;
153 }
154
155
156 /// PadLT - Order landing pads lexicographically by type id.
157 static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
158   const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
159   unsigned LSize = LIds.size(), RSize = RIds.size();
160   unsigned MinSize = LSize < RSize ? LSize : RSize;
161
162   for (unsigned i = 0; i != MinSize; ++i)
163     if (LIds[i] != RIds[i])
164       return LIds[i] < RIds[i];
165
166   return LSize < RSize;
167 }
168
169 namespace {
170
171 struct KeyInfo {
172   static inline unsigned getEmptyKey() { return -1U; }
173   static inline unsigned getTombstoneKey() { return -2U; }
174   static unsigned getHashValue(const unsigned &Key) { return Key; }
175   static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
176   static bool isPod() { return true; }
177 };
178
179 /// ActionEntry - Structure describing an entry in the actions table.
180 struct ActionEntry {
181   int ValueForTypeID; // The value to write - may not be equal to the type id.
182   int NextAction;
183   struct ActionEntry *Previous;
184 };
185
186 /// PadRange - Structure holding a try-range and the associated landing pad.
187 struct PadRange {
188   // The index of the landing pad.
189   unsigned PadIndex;
190   // The index of the begin and end labels in the landing pad's label lists.
191   unsigned RangeIndex;
192 };
193
194 typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
195
196 /// CallSiteEntry - Structure describing an entry in the call-site table.
197 struct CallSiteEntry {
198   unsigned BeginLabel; // zero indicates the start of the function.
199   unsigned EndLabel;   // zero indicates the end of the function.
200   unsigned PadLabel;   // zero indicates that there is no landing pad.
201   unsigned Action;
202 };
203
204 }
205
206 unsigned char* JITDwarfEmitter::EmitExceptionTable(MachineFunction* MF,
207                                          unsigned char* StartFunction,
208                                          unsigned char* EndFunction) const {
209   // Map all labels and get rid of any dead landing pads.
210   MMI->TidyLandingPads();
211
212   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
213   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
214   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
215   if (PadInfos.empty()) return 0;
216
217   // Sort the landing pads in order of their type ids.  This is used to fold
218   // duplicate actions.
219   SmallVector<const LandingPadInfo *, 64> LandingPads;
220   LandingPads.reserve(PadInfos.size());
221   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
222     LandingPads.push_back(&PadInfos[i]);
223   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
224
225   // Negative type ids index into FilterIds, positive type ids index into
226   // TypeInfos.  The value written for a positive type id is just the type
227   // id itself.  For a negative type id, however, the value written is the
228   // (negative) byte offset of the corresponding FilterIds entry.  The byte
229   // offset is usually equal to the type id, because the FilterIds entries
230   // are written using a variable width encoding which outputs one byte per
231   // entry as long as the value written is not too large, but can differ.
232   // This kind of complication does not occur for positive type ids because
233   // type infos are output using a fixed width encoding.
234   // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
235   SmallVector<int, 16> FilterOffsets;
236   FilterOffsets.reserve(FilterIds.size());
237   int Offset = -1;
238   for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
239     E = FilterIds.end(); I != E; ++I) {
240     FilterOffsets.push_back(Offset);
241     Offset -= MCAsmInfo::getULEB128Size(*I);
242   }
243
244   // Compute the actions table and gather the first action index for each
245   // landing pad site.
246   SmallVector<ActionEntry, 32> Actions;
247   SmallVector<unsigned, 64> FirstActions;
248   FirstActions.reserve(LandingPads.size());
249
250   int FirstAction = 0;
251   unsigned SizeActions = 0;
252   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
253     const LandingPadInfo *LP = LandingPads[i];
254     const std::vector<int> &TypeIds = LP->TypeIds;
255     const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
256     unsigned SizeSiteActions = 0;
257
258     if (NumShared < TypeIds.size()) {
259       unsigned SizeAction = 0;
260       ActionEntry *PrevAction = 0;
261
262       if (NumShared) {
263         const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
264         assert(Actions.size());
265         PrevAction = &Actions.back();
266         SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
267           MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
268         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
269           SizeAction -= MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
270           SizeAction += -PrevAction->NextAction;
271           PrevAction = PrevAction->Previous;
272         }
273       }
274
275       // Compute the actions.
276       for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
277         int TypeID = TypeIds[I];
278         assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
279         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
280         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
281
282         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
283         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
284         SizeSiteActions += SizeAction;
285
286         ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
287         Actions.push_back(Action);
288
289         PrevAction = &Actions.back();
290       }
291
292       // Record the first action of the landing pad site.
293       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
294     } // else identical - re-use previous FirstAction
295
296     FirstActions.push_back(FirstAction);
297
298     // Compute this sites contribution to size.
299     SizeActions += SizeSiteActions;
300   }
301
302   // Compute the call-site table.  Entries must be ordered by address.
303   SmallVector<CallSiteEntry, 64> CallSites;
304
305   RangeMapType PadMap;
306   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
307     const LandingPadInfo *LandingPad = LandingPads[i];
308     for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
309       unsigned BeginLabel = LandingPad->BeginLabels[j];
310       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
311       PadRange P = { i, j };
312       PadMap[BeginLabel] = P;
313     }
314   }
315
316   bool MayThrow = false;
317   unsigned LastLabel = 0;
318   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
319         I != E; ++I) {
320     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
321           MI != E; ++MI) {
322       if (!MI->isLabel()) {
323         MayThrow |= MI->getDesc().isCall();
324         continue;
325       }
326
327       unsigned BeginLabel = MI->getOperand(0).getImm();
328       assert(BeginLabel && "Invalid label!");
329
330       if (BeginLabel == LastLabel)
331         MayThrow = false;
332
333       RangeMapType::iterator L = PadMap.find(BeginLabel);
334
335       if (L == PadMap.end())
336         continue;
337
338       PadRange P = L->second;
339       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
340
341       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
342               "Inconsistent landing pad map!");
343
344       // If some instruction between the previous try-range and this one may
345       // throw, create a call-site entry with no landing pad for the region
346       // between the try-ranges.
347       if (MayThrow) {
348         CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
349         CallSites.push_back(Site);
350       }
351
352       LastLabel = LandingPad->EndLabels[P.RangeIndex];
353       CallSiteEntry Site = {BeginLabel, LastLabel,
354         LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
355
356       assert(Site.BeginLabel && Site.EndLabel && Site.PadLabel &&
357               "Invalid landing pad!");
358
359       // Try to merge with the previous call-site.
360       if (CallSites.size()) {
361         CallSiteEntry &Prev = CallSites.back();
362         if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
363           // Extend the range of the previous entry.
364           Prev.EndLabel = Site.EndLabel;
365           continue;
366         }
367       }
368
369       // Otherwise, create a new call-site.
370       CallSites.push_back(Site);
371     }
372   }
373   // If some instruction between the previous try-range and the end of the
374   // function may throw, create a call-site entry with no landing pad for the
375   // region following the try-range.
376   if (MayThrow) {
377     CallSiteEntry Site = {LastLabel, 0, 0, 0};
378     CallSites.push_back(Site);
379   }
380
381   // Final tallies.
382   unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
383                                             sizeof(int32_t) + // Site length.
384                                             sizeof(int32_t)); // Landing pad.
385   for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
386     SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
387
388   unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
389
390   unsigned TypeOffset = sizeof(int8_t) + // Call site format
391                         // Call-site table length
392                         MCAsmInfo::getULEB128Size(SizeSites) + 
393                         SizeSites + SizeActions + SizeTypes;
394
395   // Begin the exception table.
396   JCE->emitAlignmentWithFill(4, 0);
397   // Asm->EOL("Padding");
398
399   unsigned char* DwarfExceptionTable = (unsigned char*)JCE->getCurrentPCValue();
400
401   // Emit the header.
402   JCE->emitByte(dwarf::DW_EH_PE_omit);
403   // Asm->EOL("LPStart format (DW_EH_PE_omit)");
404   JCE->emitByte(dwarf::DW_EH_PE_absptr);
405   // Asm->EOL("TType format (DW_EH_PE_absptr)");
406   JCE->emitULEB128Bytes(TypeOffset);
407   // Asm->EOL("TType base offset");
408   JCE->emitByte(dwarf::DW_EH_PE_udata4);
409   // Asm->EOL("Call site format (DW_EH_PE_udata4)");
410   JCE->emitULEB128Bytes(SizeSites);
411   // Asm->EOL("Call-site table length");
412
413   // Emit the landing pad site information.
414   for (unsigned i = 0; i < CallSites.size(); ++i) {
415     CallSiteEntry &S = CallSites[i];
416     intptr_t BeginLabelPtr = 0;
417     intptr_t EndLabelPtr = 0;
418
419     if (!S.BeginLabel) {
420       BeginLabelPtr = (intptr_t)StartFunction;
421       JCE->emitInt32(0);
422     } else {
423       BeginLabelPtr = JCE->getLabelAddress(S.BeginLabel);
424       JCE->emitInt32(BeginLabelPtr - (intptr_t)StartFunction);
425     }
426
427     // Asm->EOL("Region start");
428
429     if (!S.EndLabel) {
430       EndLabelPtr = (intptr_t)EndFunction;
431       JCE->emitInt32((intptr_t)EndFunction - BeginLabelPtr);
432     } else {
433       EndLabelPtr = JCE->getLabelAddress(S.EndLabel);
434       JCE->emitInt32(EndLabelPtr - BeginLabelPtr);
435     }
436     //Asm->EOL("Region length");
437
438     if (!S.PadLabel) {
439       JCE->emitInt32(0);
440     } else {
441       unsigned PadLabelPtr = JCE->getLabelAddress(S.PadLabel);
442       JCE->emitInt32(PadLabelPtr - (intptr_t)StartFunction);
443     }
444     // Asm->EOL("Landing pad");
445
446     JCE->emitULEB128Bytes(S.Action);
447     // Asm->EOL("Action");
448   }
449
450   // Emit the actions.
451   for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
452     ActionEntry &Action = Actions[I];
453
454     JCE->emitSLEB128Bytes(Action.ValueForTypeID);
455     //Asm->EOL("TypeInfo index");
456     JCE->emitSLEB128Bytes(Action.NextAction);
457     //Asm->EOL("Next action");
458   }
459
460   // Emit the type ids.
461   for (unsigned M = TypeInfos.size(); M; --M) {
462     GlobalVariable *GV = TypeInfos[M - 1];
463     
464     if (GV) {
465       if (TD->getPointerSize() == sizeof(int32_t))
466         JCE->emitInt32((intptr_t)Jit.getOrEmitGlobalVariable(GV));
467       else
468         JCE->emitInt64((intptr_t)Jit.getOrEmitGlobalVariable(GV));
469     } else {
470       if (TD->getPointerSize() == sizeof(int32_t))
471         JCE->emitInt32(0);
472       else
473         JCE->emitInt64(0);
474     }
475     // Asm->EOL("TypeInfo");
476   }
477
478   // Emit the filter typeids.
479   for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
480     unsigned TypeID = FilterIds[j];
481     JCE->emitULEB128Bytes(TypeID);
482     //Asm->EOL("Filter TypeInfo index");
483   }
484
485   JCE->emitAlignmentWithFill(4, 0);
486
487   return DwarfExceptionTable;
488 }
489
490 unsigned char*
491 JITDwarfEmitter::EmitCommonEHFrame(const Function* Personality) const {
492   unsigned PointerSize = TD->getPointerSize();
493   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
494           PointerSize : -PointerSize;
495   
496   unsigned char* StartCommonPtr = (unsigned char*)JCE->getCurrentPCValue();
497   // EH Common Frame header
498   JCE->allocateSpace(4, 0);
499   unsigned char* FrameCommonBeginPtr = (unsigned char*)JCE->getCurrentPCValue();
500   JCE->emitInt32((int)0);
501   JCE->emitByte(dwarf::DW_CIE_VERSION);
502   JCE->emitString(Personality ? "zPLR" : "zR");
503   JCE->emitULEB128Bytes(1);
504   JCE->emitSLEB128Bytes(stackGrowth);
505   JCE->emitByte(RI->getDwarfRegNum(RI->getRARegister(), true));
506
507   if (Personality) {
508     // Augmentation Size: 3 small ULEBs of one byte each, and the personality
509     // function which size is PointerSize.
510     JCE->emitULEB128Bytes(3 + PointerSize); 
511     
512     // We set the encoding of the personality as direct encoding because we use
513     // the function pointer. The encoding is not relative because the current
514     // PC value may be bigger than the personality function pointer.
515     if (PointerSize == 4) {
516       JCE->emitByte(dwarf::DW_EH_PE_sdata4); 
517       JCE->emitInt32(((intptr_t)Jit.getPointerToGlobal(Personality)));
518     } else {
519       JCE->emitByte(dwarf::DW_EH_PE_sdata8);
520       JCE->emitInt64(((intptr_t)Jit.getPointerToGlobal(Personality)));
521     }
522
523     JCE->emitULEB128Bytes(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
524     JCE->emitULEB128Bytes(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
525   } else {
526     JCE->emitULEB128Bytes(1);
527     JCE->emitULEB128Bytes(dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4);
528   }
529
530   std::vector<MachineMove> Moves;
531   RI->getInitialFrameState(Moves);
532   EmitFrameMoves(0, Moves);
533
534   JCE->emitAlignmentWithFill(PointerSize, dwarf::DW_CFA_nop);
535
536   JCE->emitInt32At((uintptr_t*)StartCommonPtr,
537                    (uintptr_t)((unsigned char*)JCE->getCurrentPCValue() -
538                                FrameCommonBeginPtr));
539
540   return StartCommonPtr;
541 }
542
543
544 unsigned char*
545 JITDwarfEmitter::EmitEHFrame(const Function* Personality,
546                              unsigned char* StartCommonPtr,
547                              unsigned char* StartFunction, 
548                              unsigned char* EndFunction,
549                              unsigned char* ExceptionTable) const {
550   unsigned PointerSize = TD->getPointerSize();
551   
552   // EH frame header.
553   unsigned char* StartEHPtr = (unsigned char*)JCE->getCurrentPCValue();
554   JCE->allocateSpace(4, 0);
555   unsigned char* FrameBeginPtr = (unsigned char*)JCE->getCurrentPCValue();
556   // FDE CIE Offset
557   JCE->emitInt32(FrameBeginPtr - StartCommonPtr);
558   JCE->emitInt32(StartFunction - (unsigned char*)JCE->getCurrentPCValue());
559   JCE->emitInt32(EndFunction - StartFunction);
560
561   // If there is a personality and landing pads then point to the language
562   // specific data area in the exception table.
563   if (Personality) {
564     JCE->emitULEB128Bytes(PointerSize == 4 ? 4 : 8);
565         
566     if (PointerSize == 4) {
567       if (!MMI->getLandingPads().empty())
568         JCE->emitInt32(ExceptionTable-(unsigned char*)JCE->getCurrentPCValue());
569       else
570         JCE->emitInt32((int)0);
571     } else {
572       if (!MMI->getLandingPads().empty())
573         JCE->emitInt64(ExceptionTable-(unsigned char*)JCE->getCurrentPCValue());
574       else
575         JCE->emitInt64((int)0);
576     }
577   } else {
578     JCE->emitULEB128Bytes(0);
579   }
580       
581   // Indicate locations of function specific  callee saved registers in
582   // frame.
583   EmitFrameMoves((intptr_t)StartFunction, MMI->getFrameMoves());
584
585   JCE->emitAlignmentWithFill(PointerSize, dwarf::DW_CFA_nop);
586
587   // Indicate the size of the table
588   JCE->emitInt32At((uintptr_t*)StartEHPtr,
589                    (uintptr_t)((unsigned char*)JCE->getCurrentPCValue() -
590                                StartEHPtr));
591
592   // Double zeroes for the unwind runtime
593   if (PointerSize == 8) {
594     JCE->emitInt64(0);
595     JCE->emitInt64(0);
596   } else {
597     JCE->emitInt32(0);
598     JCE->emitInt32(0);
599   }
600   
601   return StartEHPtr;
602 }
603
604 unsigned JITDwarfEmitter::GetDwarfTableSizeInBytes(MachineFunction& F,
605                                          JITCodeEmitter& jce,
606                                          unsigned char* StartFunction,
607                                          unsigned char* EndFunction) {
608   const TargetMachine& TM = F.getTarget();
609   TD = TM.getTargetData();
610   stackGrowthDirection = TM.getFrameInfo()->getStackGrowthDirection();
611   RI = TM.getRegisterInfo();
612   JCE = &jce;
613   unsigned FinalSize = 0;
614   
615   FinalSize += GetExceptionTableSizeInBytes(&F);
616       
617   const std::vector<Function *> Personalities = MMI->getPersonalities();
618   FinalSize += 
619     GetCommonEHFrameSizeInBytes(Personalities[MMI->getPersonalityIndex()]);
620
621   FinalSize += GetEHFrameSizeInBytes(Personalities[MMI->getPersonalityIndex()],
622                                      StartFunction);
623
624   return FinalSize;
625 }
626
627 /// RoundUpToAlign - Add the specified alignment to FinalSize and returns
628 /// the new value.
629 static unsigned RoundUpToAlign(unsigned FinalSize, unsigned Alignment) {
630   if (Alignment == 0) Alignment = 1;
631   // Since we do not know where the buffer will be allocated, be pessimistic.
632   return FinalSize + Alignment;
633 }
634   
635 unsigned
636 JITDwarfEmitter::GetEHFrameSizeInBytes(const Function* Personality,
637                                        unsigned char* StartFunction) const { 
638   unsigned PointerSize = TD->getPointerSize();
639   unsigned FinalSize = 0;
640   // EH frame header.
641   FinalSize += PointerSize;
642   // FDE CIE Offset
643   FinalSize += 3 * PointerSize;
644   // If there is a personality and landing pads then point to the language
645   // specific data area in the exception table.
646   if (Personality) {
647     FinalSize += MCAsmInfo::getULEB128Size(4); 
648     FinalSize += PointerSize;
649   } else {
650     FinalSize += MCAsmInfo::getULEB128Size(0);
651   }
652       
653   // Indicate locations of function specific  callee saved registers in
654   // frame.
655   FinalSize += GetFrameMovesSizeInBytes((intptr_t)StartFunction,
656                                         MMI->getFrameMoves());
657       
658   FinalSize = RoundUpToAlign(FinalSize, 4);
659   
660   // Double zeroes for the unwind runtime
661   FinalSize += 2 * PointerSize;
662
663   return FinalSize;
664 }
665
666 unsigned JITDwarfEmitter::GetCommonEHFrameSizeInBytes(const Function* Personality) 
667   const {
668
669   unsigned PointerSize = TD->getPointerSize();
670   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
671           PointerSize : -PointerSize;
672   unsigned FinalSize = 0; 
673   // EH Common Frame header
674   FinalSize += PointerSize;
675   FinalSize += 4;
676   FinalSize += 1;
677   FinalSize += Personality ? 5 : 3; // "zPLR" or "zR"
678   FinalSize += MCAsmInfo::getULEB128Size(1);
679   FinalSize += MCAsmInfo::getSLEB128Size(stackGrowth);
680   FinalSize += 1;
681   
682   if (Personality) {
683     FinalSize += MCAsmInfo::getULEB128Size(7);
684     
685     // Encoding
686     FinalSize+= 1;
687     //Personality
688     FinalSize += PointerSize;
689     
690     FinalSize += MCAsmInfo::getULEB128Size(dwarf::DW_EH_PE_pcrel);
691     FinalSize += MCAsmInfo::getULEB128Size(dwarf::DW_EH_PE_pcrel);
692       
693   } else {
694     FinalSize += MCAsmInfo::getULEB128Size(1);
695     FinalSize += MCAsmInfo::getULEB128Size(dwarf::DW_EH_PE_pcrel);
696   }
697
698   std::vector<MachineMove> Moves;
699   RI->getInitialFrameState(Moves);
700   FinalSize += GetFrameMovesSizeInBytes(0, Moves);
701   FinalSize = RoundUpToAlign(FinalSize, 4);
702   return FinalSize;
703 }
704
705 unsigned
706 JITDwarfEmitter::GetFrameMovesSizeInBytes(intptr_t BaseLabelPtr,
707                                   const std::vector<MachineMove> &Moves) const {
708   unsigned PointerSize = TD->getPointerSize();
709   int stackGrowth = stackGrowthDirection == TargetFrameInfo::StackGrowsUp ?
710           PointerSize : -PointerSize;
711   bool IsLocal = BaseLabelPtr;
712   unsigned FinalSize = 0; 
713
714   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
715     const MachineMove &Move = Moves[i];
716     unsigned LabelID = Move.getLabelID();
717     
718     if (LabelID) {
719       LabelID = MMI->MappedLabel(LabelID);
720     
721       // Throw out move if the label is invalid.
722       if (!LabelID) continue;
723     }
724     
725     intptr_t LabelPtr = 0;
726     if (LabelID) LabelPtr = JCE->getLabelAddress(LabelID);
727
728     const MachineLocation &Dst = Move.getDestination();
729     const MachineLocation &Src = Move.getSource();
730     
731     // Advance row if new location.
732     if (BaseLabelPtr && LabelID && (BaseLabelPtr != LabelPtr || !IsLocal)) {
733       FinalSize++;
734       FinalSize += PointerSize;
735       BaseLabelPtr = LabelPtr;
736       IsLocal = true;
737     }
738     
739     // If advancing cfa.
740     if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
741       if (!Src.isReg()) {
742         if (Src.getReg() == MachineLocation::VirtualFP) {
743           ++FinalSize;
744         } else {
745           ++FinalSize;
746           unsigned RegNum = RI->getDwarfRegNum(Src.getReg(), true);
747           FinalSize += MCAsmInfo::getULEB128Size(RegNum);
748         }
749         
750         int Offset = -Src.getOffset();
751         
752         FinalSize += MCAsmInfo::getULEB128Size(Offset);
753       } else {
754         llvm_unreachable("Machine move no supported yet.");
755       }
756     } else if (Src.isReg() &&
757       Src.getReg() == MachineLocation::VirtualFP) {
758       if (Dst.isReg()) {
759         ++FinalSize;
760         unsigned RegNum = RI->getDwarfRegNum(Dst.getReg(), true);
761         FinalSize += MCAsmInfo::getULEB128Size(RegNum);
762       } else {
763         llvm_unreachable("Machine move no supported yet.");
764       }
765     } else {
766       unsigned Reg = RI->getDwarfRegNum(Src.getReg(), true);
767       int Offset = Dst.getOffset() / stackGrowth;
768       
769       if (Offset < 0) {
770         ++FinalSize;
771         FinalSize += MCAsmInfo::getULEB128Size(Reg);
772         FinalSize += MCAsmInfo::getSLEB128Size(Offset);
773       } else if (Reg < 64) {
774         ++FinalSize;
775         FinalSize += MCAsmInfo::getULEB128Size(Offset);
776       } else {
777         ++FinalSize;
778         FinalSize += MCAsmInfo::getULEB128Size(Reg);
779         FinalSize += MCAsmInfo::getULEB128Size(Offset);
780       }
781     }
782   }
783   return FinalSize;
784 }
785
786 unsigned 
787 JITDwarfEmitter::GetExceptionTableSizeInBytes(MachineFunction* MF) const {
788   unsigned FinalSize = 0;
789
790   // Map all labels and get rid of any dead landing pads.
791   MMI->TidyLandingPads();
792
793   const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
794   const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
795   const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
796   if (PadInfos.empty()) return 0;
797
798   // Sort the landing pads in order of their type ids.  This is used to fold
799   // duplicate actions.
800   SmallVector<const LandingPadInfo *, 64> LandingPads;
801   LandingPads.reserve(PadInfos.size());
802   for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
803     LandingPads.push_back(&PadInfos[i]);
804   std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
805
806   // Negative type ids index into FilterIds, positive type ids index into
807   // TypeInfos.  The value written for a positive type id is just the type
808   // id itself.  For a negative type id, however, the value written is the
809   // (negative) byte offset of the corresponding FilterIds entry.  The byte
810   // offset is usually equal to the type id, because the FilterIds entries
811   // are written using a variable width encoding which outputs one byte per
812   // entry as long as the value written is not too large, but can differ.
813   // This kind of complication does not occur for positive type ids because
814   // type infos are output using a fixed width encoding.
815   // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
816   SmallVector<int, 16> FilterOffsets;
817   FilterOffsets.reserve(FilterIds.size());
818   int Offset = -1;
819   for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
820     E = FilterIds.end(); I != E; ++I) {
821     FilterOffsets.push_back(Offset);
822     Offset -= MCAsmInfo::getULEB128Size(*I);
823   }
824
825   // Compute the actions table and gather the first action index for each
826   // landing pad site.
827   SmallVector<ActionEntry, 32> Actions;
828   SmallVector<unsigned, 64> FirstActions;
829   FirstActions.reserve(LandingPads.size());
830
831   int FirstAction = 0;
832   unsigned SizeActions = 0;
833   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
834     const LandingPadInfo *LP = LandingPads[i];
835     const std::vector<int> &TypeIds = LP->TypeIds;
836     const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
837     unsigned SizeSiteActions = 0;
838
839     if (NumShared < TypeIds.size()) {
840       unsigned SizeAction = 0;
841       ActionEntry *PrevAction = 0;
842
843       if (NumShared) {
844         const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
845         assert(Actions.size());
846         PrevAction = &Actions.back();
847         SizeAction = MCAsmInfo::getSLEB128Size(PrevAction->NextAction) +
848           MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
849         for (unsigned j = NumShared; j != SizePrevIds; ++j) {
850           SizeAction -= MCAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
851           SizeAction += -PrevAction->NextAction;
852           PrevAction = PrevAction->Previous;
853         }
854       }
855
856       // Compute the actions.
857       for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
858         int TypeID = TypeIds[I];
859         assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
860         int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
861         unsigned SizeTypeID = MCAsmInfo::getSLEB128Size(ValueForTypeID);
862
863         int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
864         SizeAction = SizeTypeID + MCAsmInfo::getSLEB128Size(NextAction);
865         SizeSiteActions += SizeAction;
866
867         ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
868         Actions.push_back(Action);
869
870         PrevAction = &Actions.back();
871       }
872
873       // Record the first action of the landing pad site.
874       FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
875     } // else identical - re-use previous FirstAction
876
877     FirstActions.push_back(FirstAction);
878
879     // Compute this sites contribution to size.
880     SizeActions += SizeSiteActions;
881   }
882
883   // Compute the call-site table.  Entries must be ordered by address.
884   SmallVector<CallSiteEntry, 64> CallSites;
885
886   RangeMapType PadMap;
887   for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
888     const LandingPadInfo *LandingPad = LandingPads[i];
889     for (unsigned j=0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
890       unsigned BeginLabel = LandingPad->BeginLabels[j];
891       assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
892       PadRange P = { i, j };
893       PadMap[BeginLabel] = P;
894     }
895   }
896
897   bool MayThrow = false;
898   unsigned LastLabel = 0;
899   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
900         I != E; ++I) {
901     for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
902           MI != E; ++MI) {
903       if (!MI->isLabel()) {
904         MayThrow |= MI->getDesc().isCall();
905         continue;
906       }
907
908       unsigned BeginLabel = MI->getOperand(0).getImm();
909       assert(BeginLabel && "Invalid label!");
910
911       if (BeginLabel == LastLabel)
912         MayThrow = false;
913
914       RangeMapType::iterator L = PadMap.find(BeginLabel);
915
916       if (L == PadMap.end())
917         continue;
918
919       PadRange P = L->second;
920       const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
921
922       assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
923               "Inconsistent landing pad map!");
924
925       // If some instruction between the previous try-range and this one may
926       // throw, create a call-site entry with no landing pad for the region
927       // between the try-ranges.
928       if (MayThrow) {
929         CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
930         CallSites.push_back(Site);
931       }
932
933       LastLabel = LandingPad->EndLabels[P.RangeIndex];
934       CallSiteEntry Site = {BeginLabel, LastLabel,
935         LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
936
937       assert(Site.BeginLabel && Site.EndLabel && Site.PadLabel &&
938               "Invalid landing pad!");
939
940       // Try to merge with the previous call-site.
941       if (CallSites.size()) {
942         CallSiteEntry &Prev = CallSites.back();
943         if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
944           // Extend the range of the previous entry.
945           Prev.EndLabel = Site.EndLabel;
946           continue;
947         }
948       }
949
950       // Otherwise, create a new call-site.
951       CallSites.push_back(Site);
952     }
953   }
954   // If some instruction between the previous try-range and the end of the
955   // function may throw, create a call-site entry with no landing pad for the
956   // region following the try-range.
957   if (MayThrow) {
958     CallSiteEntry Site = {LastLabel, 0, 0, 0};
959     CallSites.push_back(Site);
960   }
961
962   // Final tallies.
963   unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
964                                             sizeof(int32_t) + // Site length.
965                                             sizeof(int32_t)); // Landing pad.
966   for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
967     SizeSites += MCAsmInfo::getULEB128Size(CallSites[i].Action);
968
969   unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
970
971   unsigned TypeOffset = sizeof(int8_t) + // Call site format
972                         // Call-site table length
973                         MCAsmInfo::getULEB128Size(SizeSites) + 
974                         SizeSites + SizeActions + SizeTypes;
975
976   unsigned TotalSize = sizeof(int8_t) + // LPStart format
977                        sizeof(int8_t) + // TType format
978                        MCAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
979                        TypeOffset;
980
981   unsigned SizeAlign = (4 - TotalSize) & 3;
982
983   // Begin the exception table.
984   FinalSize = RoundUpToAlign(FinalSize, 4);
985   for (unsigned i = 0; i != SizeAlign; ++i) {
986     ++FinalSize;
987   }
988   
989   unsigned PointerSize = TD->getPointerSize();
990
991   // Emit the header.
992   ++FinalSize;
993   // Asm->EOL("LPStart format (DW_EH_PE_omit)");
994   ++FinalSize;
995   // Asm->EOL("TType format (DW_EH_PE_absptr)");
996   ++FinalSize;
997   // Asm->EOL("TType base offset");
998   ++FinalSize;
999   // Asm->EOL("Call site format (DW_EH_PE_udata4)");
1000   ++FinalSize;
1001   // Asm->EOL("Call-site table length");
1002
1003   // Emit the landing pad site information.
1004   for (unsigned i = 0; i < CallSites.size(); ++i) {
1005     CallSiteEntry &S = CallSites[i];
1006
1007     // Asm->EOL("Region start");
1008     FinalSize += PointerSize;
1009     
1010     //Asm->EOL("Region length");
1011     FinalSize += PointerSize;
1012
1013     // Asm->EOL("Landing pad");
1014     FinalSize += PointerSize;
1015
1016     FinalSize += MCAsmInfo::getULEB128Size(S.Action);
1017     // Asm->EOL("Action");
1018   }
1019
1020   // Emit the actions.
1021   for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
1022     ActionEntry &Action = Actions[I];
1023
1024     //Asm->EOL("TypeInfo index");
1025     FinalSize += MCAsmInfo::getSLEB128Size(Action.ValueForTypeID);
1026     //Asm->EOL("Next action");
1027     FinalSize += MCAsmInfo::getSLEB128Size(Action.NextAction);
1028   }
1029
1030   // Emit the type ids.
1031   for (unsigned M = TypeInfos.size(); M; --M) {
1032     // Asm->EOL("TypeInfo");
1033     FinalSize += PointerSize;
1034   }
1035
1036   // Emit the filter typeids.
1037   for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
1038     unsigned TypeID = FilterIds[j];
1039     FinalSize += MCAsmInfo::getULEB128Size(TypeID);
1040     //Asm->EOL("Filter TypeInfo index");
1041   }
1042   
1043   FinalSize = RoundUpToAlign(FinalSize, 4);
1044
1045   return FinalSize;
1046 }