[PowerPC] Rename some more VK_PPC_ enums
[oota-llvm.git] / lib / MC / MCExpr.cpp
1 //===- MCExpr.cpp - Assembly Level Expression Implementation --------------===//
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 #define DEBUG_TYPE "mcexpr"
11 #include "llvm/MC/MCExpr.h"
12 #include "llvm/ADT/Statistic.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
25 namespace {
26 namespace stats {
27 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
28 }
29 }
30
31 void MCExpr::print(raw_ostream &OS) const {
32   switch (getKind()) {
33   case MCExpr::Target:
34     return cast<MCTargetExpr>(this)->PrintImpl(OS);
35   case MCExpr::Constant:
36     OS << cast<MCConstantExpr>(*this).getValue();
37     return;
38
39   case MCExpr::SymbolRef: {
40     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
41     const MCSymbol &Sym = SRE.getSymbol();
42     // Parenthesize names that start with $ so that they don't look like
43     // absolute names.
44     bool UseParens = Sym.getName()[0] == '$';
45     if (UseParens)
46       OS << '(' << Sym << ')';
47     else
48       OS << Sym;
49
50     if (SRE.getKind() == MCSymbolRefExpr::VK_ARM_NONE ||
51         SRE.getKind() == MCSymbolRefExpr::VK_ARM_PLT ||
52         SRE.getKind() == MCSymbolRefExpr::VK_ARM_TLSGD ||
53         SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOT ||
54         SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTOFF ||
55         SRE.getKind() == MCSymbolRefExpr::VK_ARM_TPOFF ||
56         SRE.getKind() == MCSymbolRefExpr::VK_ARM_GOTTPOFF ||
57         SRE.getKind() == MCSymbolRefExpr::VK_ARM_TARGET1 ||
58         SRE.getKind() == MCSymbolRefExpr::VK_ARM_TARGET2 ||
59         SRE.getKind() == MCSymbolRefExpr::VK_ARM_PREL31)
60       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
61     else if (SRE.getKind() != MCSymbolRefExpr::VK_None)
62       OS << '@' << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
63
64     return;
65   }
66
67   case MCExpr::Unary: {
68     const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
69     switch (UE.getOpcode()) {
70     case MCUnaryExpr::LNot:  OS << '!'; break;
71     case MCUnaryExpr::Minus: OS << '-'; break;
72     case MCUnaryExpr::Not:   OS << '~'; break;
73     case MCUnaryExpr::Plus:  OS << '+'; break;
74     }
75     OS << *UE.getSubExpr();
76     return;
77   }
78
79   case MCExpr::Binary: {
80     const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
81
82     // Only print parens around the LHS if it is non-trivial.
83     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
84       OS << *BE.getLHS();
85     } else {
86       OS << '(' << *BE.getLHS() << ')';
87     }
88
89     switch (BE.getOpcode()) {
90     case MCBinaryExpr::Add:
91       // Print "X-42" instead of "X+-42".
92       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
93         if (RHSC->getValue() < 0) {
94           OS << RHSC->getValue();
95           return;
96         }
97       }
98
99       OS <<  '+';
100       break;
101     case MCBinaryExpr::And:  OS <<  '&'; break;
102     case MCBinaryExpr::Div:  OS <<  '/'; break;
103     case MCBinaryExpr::EQ:   OS << "=="; break;
104     case MCBinaryExpr::GT:   OS <<  '>'; break;
105     case MCBinaryExpr::GTE:  OS << ">="; break;
106     case MCBinaryExpr::LAnd: OS << "&&"; break;
107     case MCBinaryExpr::LOr:  OS << "||"; break;
108     case MCBinaryExpr::LT:   OS <<  '<'; break;
109     case MCBinaryExpr::LTE:  OS << "<="; break;
110     case MCBinaryExpr::Mod:  OS <<  '%'; break;
111     case MCBinaryExpr::Mul:  OS <<  '*'; break;
112     case MCBinaryExpr::NE:   OS << "!="; break;
113     case MCBinaryExpr::Or:   OS <<  '|'; break;
114     case MCBinaryExpr::Shl:  OS << "<<"; break;
115     case MCBinaryExpr::Shr:  OS << ">>"; break;
116     case MCBinaryExpr::Sub:  OS <<  '-'; break;
117     case MCBinaryExpr::Xor:  OS <<  '^'; break;
118     }
119
120     // Only print parens around the LHS if it is non-trivial.
121     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
122       OS << *BE.getRHS();
123     } else {
124       OS << '(' << *BE.getRHS() << ')';
125     }
126     return;
127   }
128   }
129
130   llvm_unreachable("Invalid expression kind!");
131 }
132
133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
134 void MCExpr::dump() const {
135   print(dbgs());
136   dbgs() << '\n';
137 }
138 #endif
139
140 /* *** */
141
142 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
143                                          const MCExpr *RHS, MCContext &Ctx) {
144   return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
145 }
146
147 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
148                                        MCContext &Ctx) {
149   return new (Ctx) MCUnaryExpr(Opc, Expr);
150 }
151
152 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
153   return new (Ctx) MCConstantExpr(Value);
154 }
155
156 /* *** */
157
158 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
159                                                VariantKind Kind,
160                                                MCContext &Ctx) {
161   return new (Ctx) MCSymbolRefExpr(Sym, Kind);
162 }
163
164 const MCSymbolRefExpr *MCSymbolRefExpr::Create(StringRef Name, VariantKind Kind,
165                                                MCContext &Ctx) {
166   return Create(Ctx.GetOrCreateSymbol(Name), Kind, Ctx);
167 }
168
169 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
170   switch (Kind) {
171   case VK_Invalid: return "<<invalid>>";
172   case VK_None: return "<<none>>";
173
174   case VK_GOT: return "GOT";
175   case VK_GOTOFF: return "GOTOFF";
176   case VK_GOTPCREL: return "GOTPCREL";
177   case VK_GOTTPOFF: return "GOTTPOFF";
178   case VK_INDNTPOFF: return "INDNTPOFF";
179   case VK_NTPOFF: return "NTPOFF";
180   case VK_GOTNTPOFF: return "GOTNTPOFF";
181   case VK_PLT: return "PLT";
182   case VK_TLSGD: return "TLSGD";
183   case VK_TLSLD: return "TLSLD";
184   case VK_TLSLDM: return "TLSLDM";
185   case VK_TPOFF: return "TPOFF";
186   case VK_DTPOFF: return "DTPOFF";
187   case VK_TLVP: return "TLVP";
188   case VK_SECREL: return "SECREL32";
189   case VK_ARM_NONE: return "(NONE)";
190   case VK_ARM_PLT: return "(PLT)";
191   case VK_ARM_GOT: return "(GOT)";
192   case VK_ARM_GOTOFF: return "(GOTOFF)";
193   case VK_ARM_TPOFF: return "(tpoff)";
194   case VK_ARM_GOTTPOFF: return "(gottpoff)";
195   case VK_ARM_TLSGD: return "(tlsgd)";
196   case VK_ARM_TARGET1: return "(target1)";
197   case VK_ARM_TARGET2: return "(target2)";
198   case VK_ARM_PREL31: return "(prel31)";
199   case VK_PPC_LO: return "l";
200   case VK_PPC_HA: return "ha";
201   case VK_PPC_TOCBASE: return "tocbase";
202   case VK_PPC_TOC: return "toc";
203   case VK_PPC_TOC_LO: return "toc@l";
204   case VK_PPC_TOC_HA: return "toc@ha";
205   case VK_PPC_TPREL_LO: return "tprel@l";
206   case VK_PPC_TPREL_HA: return "tprel@ha";
207   case VK_PPC_DTPREL_LO: return "dtprel@l";
208   case VK_PPC_DTPREL_HA: return "dtprel@ha";
209   case VK_PPC_GOT_TPREL_LO: return "got@tprel@l";
210   case VK_PPC_GOT_TPREL_HA: return "got@tprel@ha";
211   case VK_PPC_TLS: return "tls";
212   case VK_PPC_GOT_TLSGD_LO: return "got@tlsgd@l";
213   case VK_PPC_GOT_TLSGD_HA: return "got@tlsgd@ha";
214   case VK_PPC_TLSGD: return "tlsgd";
215   case VK_PPC_GOT_TLSLD_LO: return "got@tlsld@l";
216   case VK_PPC_GOT_TLSLD_HA: return "got@tlsld@ha";
217   case VK_PPC_TLSLD: return "tlsld";
218   case VK_Mips_GPREL: return "GPREL";
219   case VK_Mips_GOT_CALL: return "GOT_CALL";
220   case VK_Mips_GOT16: return "GOT16";
221   case VK_Mips_GOT: return "GOT";
222   case VK_Mips_ABS_HI: return "ABS_HI";
223   case VK_Mips_ABS_LO: return "ABS_LO";
224   case VK_Mips_TLSGD: return "TLSGD";
225   case VK_Mips_TLSLDM: return "TLSLDM";
226   case VK_Mips_DTPREL_HI: return "DTPREL_HI";
227   case VK_Mips_DTPREL_LO: return "DTPREL_LO";
228   case VK_Mips_GOTTPREL: return "GOTTPREL";
229   case VK_Mips_TPREL_HI: return "TPREL_HI";
230   case VK_Mips_TPREL_LO: return "TPREL_LO";
231   case VK_Mips_GPOFF_HI: return "GPOFF_HI";
232   case VK_Mips_GPOFF_LO: return "GPOFF_LO";
233   case VK_Mips_GOT_DISP: return "GOT_DISP";
234   case VK_Mips_GOT_PAGE: return "GOT_PAGE";
235   case VK_Mips_GOT_OFST: return "GOT_OFST";
236   case VK_Mips_HIGHER:   return "HIGHER";
237   case VK_Mips_HIGHEST:  return "HIGHEST";
238   case VK_Mips_GOT_HI16: return "GOT_HI16";
239   case VK_Mips_GOT_LO16: return "GOT_LO16";
240   case VK_Mips_CALL_HI16: return "CALL_HI16";
241   case VK_Mips_CALL_LO16: return "CALL_LO16";
242   case VK_COFF_IMGREL32: return "IMGREL32";
243   }
244   llvm_unreachable("Invalid variant kind");
245 }
246
247 MCSymbolRefExpr::VariantKind
248 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
249   return StringSwitch<VariantKind>(Name)
250     .Case("GOT", VK_GOT)
251     .Case("got", VK_GOT)
252     .Case("GOTOFF", VK_GOTOFF)
253     .Case("gotoff", VK_GOTOFF)
254     .Case("GOTPCREL", VK_GOTPCREL)
255     .Case("gotpcrel", VK_GOTPCREL)
256     .Case("GOTTPOFF", VK_GOTTPOFF)
257     .Case("gottpoff", VK_GOTTPOFF)
258     .Case("INDNTPOFF", VK_INDNTPOFF)
259     .Case("indntpoff", VK_INDNTPOFF)
260     .Case("NTPOFF", VK_NTPOFF)
261     .Case("ntpoff", VK_NTPOFF)
262     .Case("GOTNTPOFF", VK_GOTNTPOFF)
263     .Case("gotntpoff", VK_GOTNTPOFF)
264     .Case("PLT", VK_PLT)
265     .Case("plt", VK_PLT)
266     .Case("TLSGD", VK_TLSGD)
267     .Case("tlsgd", VK_TLSGD)
268     .Case("TLSLD", VK_TLSLD)
269     .Case("tlsld", VK_TLSLD)
270     .Case("TLSLDM", VK_TLSLDM)
271     .Case("tlsldm", VK_TLSLDM)
272     .Case("TPOFF", VK_TPOFF)
273     .Case("tpoff", VK_TPOFF)
274     .Case("DTPOFF", VK_DTPOFF)
275     .Case("dtpoff", VK_DTPOFF)
276     .Case("TLVP", VK_TLVP)
277     .Case("tlvp", VK_TLVP)
278     .Case("IMGREL", VK_COFF_IMGREL32)
279     .Case("imgrel", VK_COFF_IMGREL32)
280     .Case("SECREL32", VK_SECREL)
281     .Case("secrel32", VK_SECREL)
282     .Case("L", VK_PPC_LO)
283     .Case("l", VK_PPC_LO)
284     .Case("HA", VK_PPC_HA)
285     .Case("ha", VK_PPC_HA)
286     .Case("TOCBASE", VK_PPC_TOCBASE)
287     .Case("tocbase", VK_PPC_TOCBASE)
288     .Case("TOC", VK_PPC_TOC)
289     .Case("toc", VK_PPC_TOC)
290     .Case("TOC@L", VK_PPC_TOC_LO)
291     .Case("toc@l", VK_PPC_TOC_LO)
292     .Case("TOC@HA", VK_PPC_TOC_HA)
293     .Case("toc@ha", VK_PPC_TOC_HA)
294     .Case("TLS", VK_PPC_TLS)
295     .Case("tls", VK_PPC_TLS)
296     .Case("TPREL@L", VK_PPC_TPREL_LO)
297     .Case("tprel@l", VK_PPC_TPREL_LO)
298     .Case("TPREL@HA", VK_PPC_TPREL_HA)
299     .Case("tprel@ha", VK_PPC_TPREL_HA)
300     .Case("DTPREL@L", VK_PPC_DTPREL_LO)
301     .Case("dtprel@l", VK_PPC_DTPREL_LO)
302     .Case("DTPREL@HA", VK_PPC_DTPREL_HA)
303     .Case("dtprel@ha", VK_PPC_DTPREL_HA)
304     .Case("GOT@TPREL@L", VK_PPC_GOT_TPREL_LO)
305     .Case("got@tprel@l", VK_PPC_GOT_TPREL_LO)
306     .Case("GOT@TPREL@HA", VK_PPC_GOT_TPREL_HA)
307     .Case("got@tprel@ha", VK_PPC_GOT_TPREL_HA)
308     .Case("GOT@TLSGD@L", VK_PPC_GOT_TLSGD_LO)
309     .Case("got@tlsgd@l", VK_PPC_GOT_TLSGD_LO)
310     .Case("GOT@TLSGD@HA", VK_PPC_GOT_TLSGD_HA)
311     .Case("got@tlsgd@ha", VK_PPC_GOT_TLSGD_HA)
312     .Case("GOT@TLSLD@L", VK_PPC_GOT_TLSLD_LO)
313     .Case("got@tlsld@l", VK_PPC_GOT_TLSLD_LO)
314     .Case("GOT@TLSLD@HA", VK_PPC_GOT_TLSLD_HA)
315     .Case("got@tlsld@ha", VK_PPC_GOT_TLSLD_HA)
316     .Default(VK_Invalid);
317 }
318
319 /* *** */
320
321 void MCTargetExpr::anchor() {}
322
323 /* *** */
324
325 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
326   return EvaluateAsAbsolute(Res, 0, 0, 0);
327 }
328
329 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
330                                 const MCAsmLayout &Layout) const {
331   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, 0);
332 }
333
334 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
335                                 const MCAsmLayout &Layout,
336                                 const SectionAddrMap &Addrs) const {
337   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
338 }
339
340 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
341   return EvaluateAsAbsolute(Res, &Asm, 0, 0);
342 }
343
344 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
345                                 const MCAsmLayout *Layout,
346                                 const SectionAddrMap *Addrs) const {
347   MCValue Value;
348
349   // Fast path constants.
350   if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
351     Res = CE->getValue();
352     return true;
353   }
354
355   // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
356   // absolutize differences across sections and that is what the MachO writer
357   // uses Addrs for.
358   bool IsRelocatable =
359     EvaluateAsRelocatableImpl(Value, Asm, Layout, Addrs, /*InSet*/ Addrs);
360
361   // Record the current value.
362   Res = Value.getConstant();
363
364   return IsRelocatable && Value.isAbsolute();
365 }
366
367 /// \brief Helper method for \see EvaluateSymbolAdd().
368 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
369                                                 const MCAsmLayout *Layout,
370                                                 const SectionAddrMap *Addrs,
371                                                 bool InSet,
372                                                 const MCSymbolRefExpr *&A,
373                                                 const MCSymbolRefExpr *&B,
374                                                 int64_t &Addend) {
375   if (!A || !B)
376     return;
377
378   const MCSymbol &SA = A->getSymbol();
379   const MCSymbol &SB = B->getSymbol();
380
381   if (SA.isUndefined() || SB.isUndefined())
382     return;
383
384   if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
385     return;
386
387   MCSymbolData &AD = Asm->getSymbolData(SA);
388   MCSymbolData &BD = Asm->getSymbolData(SB);
389
390   if (AD.getFragment() == BD.getFragment()) {
391     Addend += (AD.getOffset() - BD.getOffset());
392
393     // Pointers to Thumb symbols need to have their low-bit set to allow
394     // for interworking.
395     if (Asm->isThumbFunc(&SA))
396       Addend |= 1;
397
398     // Clear the symbol expr pointers to indicate we have folded these
399     // operands.
400     A = B = 0;
401     return;
402   }
403
404   if (!Layout)
405     return;
406
407   const MCSectionData &SecA = *AD.getFragment()->getParent();
408   const MCSectionData &SecB = *BD.getFragment()->getParent();
409
410   if ((&SecA != &SecB) && !Addrs)
411     return;
412
413   // Eagerly evaluate.
414   Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
415              Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
416   if (Addrs && (&SecA != &SecB))
417     Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
418
419   // Pointers to Thumb symbols need to have their low-bit set to allow
420   // for interworking.
421   if (Asm->isThumbFunc(&SA))
422     Addend |= 1;
423
424   // Clear the symbol expr pointers to indicate we have folded these
425   // operands.
426   A = B = 0;
427 }
428
429 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
430 ///
431 /// This routine conceptually attempts to construct an MCValue:
432 ///   Result = (Result_A - Result_B + Result_Cst)
433 /// from two MCValue's LHS and RHS where
434 ///   Result = LHS + RHS
435 /// and
436 ///   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
437 ///
438 /// This routine attempts to aggresively fold the operands such that the result
439 /// is representable in an MCValue, but may not always succeed.
440 ///
441 /// \returns True on success, false if the result is not representable in an
442 /// MCValue.
443
444 /// NOTE: It is really important to have both the Asm and Layout arguments.
445 /// They might look redundant, but this function can be used before layout
446 /// is done (see the object streamer for example) and having the Asm argument
447 /// lets us avoid relaxations early.
448 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
449                                 const MCAsmLayout *Layout,
450                                 const SectionAddrMap *Addrs,
451                                 bool InSet,
452                                 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
453                                 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
454                                 MCValue &Res) {
455   // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
456   // about dealing with modifiers. This will ultimately bite us, one day.
457   const MCSymbolRefExpr *LHS_A = LHS.getSymA();
458   const MCSymbolRefExpr *LHS_B = LHS.getSymB();
459   int64_t LHS_Cst = LHS.getConstant();
460
461   // Fold the result constant immediately.
462   int64_t Result_Cst = LHS_Cst + RHS_Cst;
463
464   assert((!Layout || Asm) &&
465          "Must have an assembler object if layout is given!");
466
467   // If we have a layout, we can fold resolved differences.
468   if (Asm) {
469     // First, fold out any differences which are fully resolved. By
470     // reassociating terms in
471     //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
472     // we have the four possible differences:
473     //   (LHS_A - LHS_B),
474     //   (LHS_A - RHS_B),
475     //   (RHS_A - LHS_B),
476     //   (RHS_A - RHS_B).
477     // Since we are attempting to be as aggressive as possible about folding, we
478     // attempt to evaluate each possible alternative.
479     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
480                                         Result_Cst);
481     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
482                                         Result_Cst);
483     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
484                                         Result_Cst);
485     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
486                                         Result_Cst);
487   }
488
489   // We can't represent the addition or subtraction of two symbols.
490   if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
491     return false;
492
493   // At this point, we have at most one additive symbol and one subtractive
494   // symbol -- find them.
495   const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
496   const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
497
498   // If we have a negated symbol, then we must have also have a non-negated
499   // symbol in order to encode the expression.
500   if (B && !A)
501     return false;
502
503   Res = MCValue::get(A, B, Result_Cst);
504   return true;
505 }
506
507 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
508                                    const MCAsmLayout &Layout) const {
509   return EvaluateAsRelocatableImpl(Res, &Layout.getAssembler(), &Layout,
510                                    0, false);
511 }
512
513 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res,
514                                        const MCAssembler *Asm,
515                                        const MCAsmLayout *Layout,
516                                        const SectionAddrMap *Addrs,
517                                        bool InSet) const {
518   ++stats::MCExprEvaluate;
519
520   switch (getKind()) {
521   case Target:
522     return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout);
523
524   case Constant:
525     Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
526     return true;
527
528   case SymbolRef: {
529     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
530     const MCSymbol &Sym = SRE->getSymbol();
531
532     // Evaluate recursively if this is a variable.
533     if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
534       bool Ret = Sym.getVariableValue()->EvaluateAsRelocatableImpl(Res, Asm,
535                                                                    Layout,
536                                                                    Addrs,
537                                                                    true);
538       // If we failed to simplify this to a constant, let the target
539       // handle it.
540       if (Ret && !Res.getSymA() && !Res.getSymB())
541         return true;
542     }
543
544     Res = MCValue::get(SRE, 0, 0);
545     return true;
546   }
547
548   case Unary: {
549     const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
550     MCValue Value;
551
552     if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
553                                                       Addrs, InSet))
554       return false;
555
556     switch (AUE->getOpcode()) {
557     case MCUnaryExpr::LNot:
558       if (!Value.isAbsolute())
559         return false;
560       Res = MCValue::get(!Value.getConstant());
561       break;
562     case MCUnaryExpr::Minus:
563       /// -(a - b + const) ==> (b - a - const)
564       if (Value.getSymA() && !Value.getSymB())
565         return false;
566       Res = MCValue::get(Value.getSymB(), Value.getSymA(),
567                          -Value.getConstant());
568       break;
569     case MCUnaryExpr::Not:
570       if (!Value.isAbsolute())
571         return false;
572       Res = MCValue::get(~Value.getConstant());
573       break;
574     case MCUnaryExpr::Plus:
575       Res = Value;
576       break;
577     }
578
579     return true;
580   }
581
582   case Binary: {
583     const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
584     MCValue LHSValue, RHSValue;
585
586     if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
587                                                   Addrs, InSet) ||
588         !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
589                                                   Addrs, InSet))
590       return false;
591
592     // We only support a few operations on non-constant expressions, handle
593     // those first.
594     if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
595       switch (ABE->getOpcode()) {
596       default:
597         return false;
598       case MCBinaryExpr::Sub:
599         // Negate RHS and add.
600         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
601                                    RHSValue.getSymB(), RHSValue.getSymA(),
602                                    -RHSValue.getConstant(),
603                                    Res);
604
605       case MCBinaryExpr::Add:
606         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
607                                    RHSValue.getSymA(), RHSValue.getSymB(),
608                                    RHSValue.getConstant(),
609                                    Res);
610       }
611     }
612
613     // FIXME: We need target hooks for the evaluation. It may be limited in
614     // width, and gas defines the result of comparisons and right shifts
615     // differently from Apple as.
616     int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
617     int64_t Result = 0;
618     switch (ABE->getOpcode()) {
619     case MCBinaryExpr::Add:  Result = LHS + RHS; break;
620     case MCBinaryExpr::And:  Result = LHS & RHS; break;
621     case MCBinaryExpr::Div:  Result = LHS / RHS; break;
622     case MCBinaryExpr::EQ:   Result = LHS == RHS; break;
623     case MCBinaryExpr::GT:   Result = LHS > RHS; break;
624     case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;
625     case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
626     case MCBinaryExpr::LOr:  Result = LHS || RHS; break;
627     case MCBinaryExpr::LT:   Result = LHS < RHS; break;
628     case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;
629     case MCBinaryExpr::Mod:  Result = LHS % RHS; break;
630     case MCBinaryExpr::Mul:  Result = LHS * RHS; break;
631     case MCBinaryExpr::NE:   Result = LHS != RHS; break;
632     case MCBinaryExpr::Or:   Result = LHS | RHS; break;
633     case MCBinaryExpr::Shl:  Result = LHS << RHS; break;
634     case MCBinaryExpr::Shr:  Result = LHS >> RHS; break;
635     case MCBinaryExpr::Sub:  Result = LHS - RHS; break;
636     case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;
637     }
638
639     Res = MCValue::get(Result);
640     return true;
641   }
642   }
643
644   llvm_unreachable("Invalid assembly expression kind!");
645 }
646
647 const MCSection *MCExpr::FindAssociatedSection() const {
648   switch (getKind()) {
649   case Target:
650     // We never look through target specific expressions.
651     return cast<MCTargetExpr>(this)->FindAssociatedSection();
652
653   case Constant:
654     return MCSymbol::AbsolutePseudoSection;
655
656   case SymbolRef: {
657     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
658     const MCSymbol &Sym = SRE->getSymbol();
659
660     if (Sym.isDefined())
661       return &Sym.getSection();
662
663     return 0;
664   }
665
666   case Unary:
667     return cast<MCUnaryExpr>(this)->getSubExpr()->FindAssociatedSection();
668
669   case Binary: {
670     const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
671     const MCSection *LHS_S = BE->getLHS()->FindAssociatedSection();
672     const MCSection *RHS_S = BE->getRHS()->FindAssociatedSection();
673
674     // If either section is absolute, return the other.
675     if (LHS_S == MCSymbol::AbsolutePseudoSection)
676       return RHS_S;
677     if (RHS_S == MCSymbol::AbsolutePseudoSection)
678       return LHS_S;
679
680     // Otherwise, return the first non-null section.
681     return LHS_S ? LHS_S : RHS_S;
682   }
683   }
684
685   llvm_unreachable("Invalid assembly expression kind!");
686 }