Thumb1 frame lowering: Mark CFI instructions with the FrameSetup flag.
[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 #include "llvm/MC/MCExpr.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/MC/MCAsmInfo.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 #define DEBUG_TYPE "mcexpr"
26
27 namespace {
28 namespace stats {
29 STATISTIC(MCExprEvaluate, "Number of MCExpr evaluations");
30 }
31 }
32
33 void MCExpr::print(raw_ostream &OS) const {
34   switch (getKind()) {
35   case MCExpr::Target:
36     return cast<MCTargetExpr>(this)->PrintImpl(OS);
37   case MCExpr::Constant:
38     OS << cast<MCConstantExpr>(*this).getValue();
39     return;
40
41   case MCExpr::SymbolRef: {
42     const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(*this);
43     const MCSymbol &Sym = SRE.getSymbol();
44     // Parenthesize names that start with $ so that they don't look like
45     // absolute names.
46     bool UseParens = Sym.getName()[0] == '$';
47     if (UseParens)
48       OS << '(' << Sym << ')';
49     else
50       OS << Sym;
51
52     if (SRE.getKind() != MCSymbolRefExpr::VK_None)
53       SRE.printVariantKind(OS);
54
55     return;
56   }
57
58   case MCExpr::Unary: {
59     const MCUnaryExpr &UE = cast<MCUnaryExpr>(*this);
60     switch (UE.getOpcode()) {
61     case MCUnaryExpr::LNot:  OS << '!'; break;
62     case MCUnaryExpr::Minus: OS << '-'; break;
63     case MCUnaryExpr::Not:   OS << '~'; break;
64     case MCUnaryExpr::Plus:  OS << '+'; break;
65     }
66     OS << *UE.getSubExpr();
67     return;
68   }
69
70   case MCExpr::Binary: {
71     const MCBinaryExpr &BE = cast<MCBinaryExpr>(*this);
72
73     // Only print parens around the LHS if it is non-trivial.
74     if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS())) {
75       OS << *BE.getLHS();
76     } else {
77       OS << '(' << *BE.getLHS() << ')';
78     }
79
80     switch (BE.getOpcode()) {
81     case MCBinaryExpr::Add:
82       // Print "X-42" instead of "X+-42".
83       if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
84         if (RHSC->getValue() < 0) {
85           OS << RHSC->getValue();
86           return;
87         }
88       }
89
90       OS <<  '+';
91       break;
92     case MCBinaryExpr::And:  OS <<  '&'; break;
93     case MCBinaryExpr::Div:  OS <<  '/'; break;
94     case MCBinaryExpr::EQ:   OS << "=="; break;
95     case MCBinaryExpr::GT:   OS <<  '>'; break;
96     case MCBinaryExpr::GTE:  OS << ">="; break;
97     case MCBinaryExpr::LAnd: OS << "&&"; break;
98     case MCBinaryExpr::LOr:  OS << "||"; break;
99     case MCBinaryExpr::LT:   OS <<  '<'; break;
100     case MCBinaryExpr::LTE:  OS << "<="; break;
101     case MCBinaryExpr::Mod:  OS <<  '%'; break;
102     case MCBinaryExpr::Mul:  OS <<  '*'; break;
103     case MCBinaryExpr::NE:   OS << "!="; break;
104     case MCBinaryExpr::Or:   OS <<  '|'; break;
105     case MCBinaryExpr::Shl:  OS << "<<"; break;
106     case MCBinaryExpr::Shr:  OS << ">>"; break;
107     case MCBinaryExpr::Sub:  OS <<  '-'; break;
108     case MCBinaryExpr::Xor:  OS <<  '^'; break;
109     }
110
111     // Only print parens around the LHS if it is non-trivial.
112     if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
113       OS << *BE.getRHS();
114     } else {
115       OS << '(' << *BE.getRHS() << ')';
116     }
117     return;
118   }
119   }
120
121   llvm_unreachable("Invalid expression kind!");
122 }
123
124 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
125 void MCExpr::dump() const {
126   print(dbgs());
127   dbgs() << '\n';
128 }
129 #endif
130
131 /* *** */
132
133 const MCBinaryExpr *MCBinaryExpr::Create(Opcode Opc, const MCExpr *LHS,
134                                          const MCExpr *RHS, MCContext &Ctx) {
135   return new (Ctx) MCBinaryExpr(Opc, LHS, RHS);
136 }
137
138 const MCUnaryExpr *MCUnaryExpr::Create(Opcode Opc, const MCExpr *Expr,
139                                        MCContext &Ctx) {
140   return new (Ctx) MCUnaryExpr(Opc, Expr);
141 }
142
143 const MCConstantExpr *MCConstantExpr::Create(int64_t Value, MCContext &Ctx) {
144   return new (Ctx) MCConstantExpr(Value);
145 }
146
147 /* *** */
148
149 MCSymbolRefExpr::MCSymbolRefExpr(const MCSymbol *Symbol, VariantKind Kind,
150                                  const MCAsmInfo *MAI)
151     : MCExpr(MCExpr::SymbolRef), Kind(Kind),
152       UseParensForSymbolVariant(MAI->useParensForSymbolVariant()),
153       HasSubsectionsViaSymbols(MAI->hasSubsectionsViaSymbols()),
154       Symbol(Symbol) {
155   assert(Symbol);
156 }
157
158 const MCSymbolRefExpr *MCSymbolRefExpr::Create(const MCSymbol *Sym,
159                                                VariantKind Kind,
160                                                MCContext &Ctx) {
161   return new (Ctx) MCSymbolRefExpr(Sym, Kind, Ctx.getAsmInfo());
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_TLVPPAGE: return "TLVPPAGE";
189   case VK_TLVPPAGEOFF: return "TLVPPAGEOFF";
190   case VK_PAGE: return "PAGE";
191   case VK_PAGEOFF: return "PAGEOFF";
192   case VK_GOTPAGE: return "GOTPAGE";
193   case VK_GOTPAGEOFF: return "GOTPAGEOFF";
194   case VK_SECREL: return "SECREL32";
195   case VK_WEAKREF: return "WEAKREF";
196   case VK_ARM_NONE: return "none";
197   case VK_ARM_TARGET1: return "target1";
198   case VK_ARM_TARGET2: return "target2";
199   case VK_ARM_PREL31: return "prel31";
200   case VK_ARM_TLSLDO: return "tlsldo";
201   case VK_ARM_TLSCALL: return "tlscall";
202   case VK_ARM_TLSDESC: return "tlsdesc";
203   case VK_ARM_TLSDESCSEQ: return "tlsdescseq";
204   case VK_PPC_LO: return "l";
205   case VK_PPC_HI: return "h";
206   case VK_PPC_HA: return "ha";
207   case VK_PPC_HIGHER: return "higher";
208   case VK_PPC_HIGHERA: return "highera";
209   case VK_PPC_HIGHEST: return "highest";
210   case VK_PPC_HIGHESTA: return "highesta";
211   case VK_PPC_GOT_LO: return "got@l";
212   case VK_PPC_GOT_HI: return "got@h";
213   case VK_PPC_GOT_HA: return "got@ha";
214   case VK_PPC_TOCBASE: return "tocbase";
215   case VK_PPC_TOC: return "toc";
216   case VK_PPC_TOC_LO: return "toc@l";
217   case VK_PPC_TOC_HI: return "toc@h";
218   case VK_PPC_TOC_HA: return "toc@ha";
219   case VK_PPC_DTPMOD: return "dtpmod";
220   case VK_PPC_TPREL: return "tprel";
221   case VK_PPC_TPREL_LO: return "tprel@l";
222   case VK_PPC_TPREL_HI: return "tprel@h";
223   case VK_PPC_TPREL_HA: return "tprel@ha";
224   case VK_PPC_TPREL_HIGHER: return "tprel@higher";
225   case VK_PPC_TPREL_HIGHERA: return "tprel@highera";
226   case VK_PPC_TPREL_HIGHEST: return "tprel@highest";
227   case VK_PPC_TPREL_HIGHESTA: return "tprel@highesta";
228   case VK_PPC_DTPREL: return "dtprel";
229   case VK_PPC_DTPREL_LO: return "dtprel@l";
230   case VK_PPC_DTPREL_HI: return "dtprel@h";
231   case VK_PPC_DTPREL_HA: return "dtprel@ha";
232   case VK_PPC_DTPREL_HIGHER: return "dtprel@higher";
233   case VK_PPC_DTPREL_HIGHERA: return "dtprel@highera";
234   case VK_PPC_DTPREL_HIGHEST: return "dtprel@highest";
235   case VK_PPC_DTPREL_HIGHESTA: return "dtprel@highesta";
236   case VK_PPC_GOT_TPREL: return "got@tprel";
237   case VK_PPC_GOT_TPREL_LO: return "got@tprel@l";
238   case VK_PPC_GOT_TPREL_HI: return "got@tprel@h";
239   case VK_PPC_GOT_TPREL_HA: return "got@tprel@ha";
240   case VK_PPC_GOT_DTPREL: return "got@dtprel";
241   case VK_PPC_GOT_DTPREL_LO: return "got@dtprel@l";
242   case VK_PPC_GOT_DTPREL_HI: return "got@dtprel@h";
243   case VK_PPC_GOT_DTPREL_HA: return "got@dtprel@ha";
244   case VK_PPC_TLS: return "tls";
245   case VK_PPC_GOT_TLSGD: return "got@tlsgd";
246   case VK_PPC_GOT_TLSGD_LO: return "got@tlsgd@l";
247   case VK_PPC_GOT_TLSGD_HI: return "got@tlsgd@h";
248   case VK_PPC_GOT_TLSGD_HA: return "got@tlsgd@ha";
249   case VK_PPC_TLSGD: return "tlsgd";
250   case VK_PPC_GOT_TLSLD: return "got@tlsld";
251   case VK_PPC_GOT_TLSLD_LO: return "got@tlsld@l";
252   case VK_PPC_GOT_TLSLD_HI: return "got@tlsld@h";
253   case VK_PPC_GOT_TLSLD_HA: return "got@tlsld@ha";
254   case VK_PPC_TLSLD: return "tlsld";
255   case VK_PPC_LOCAL: return "local";
256   case VK_Mips_GPREL: return "GPREL";
257   case VK_Mips_GOT_CALL: return "GOT_CALL";
258   case VK_Mips_GOT16: return "GOT16";
259   case VK_Mips_GOT: return "GOT";
260   case VK_Mips_ABS_HI: return "ABS_HI";
261   case VK_Mips_ABS_LO: return "ABS_LO";
262   case VK_Mips_TLSGD: return "TLSGD";
263   case VK_Mips_TLSLDM: return "TLSLDM";
264   case VK_Mips_DTPREL_HI: return "DTPREL_HI";
265   case VK_Mips_DTPREL_LO: return "DTPREL_LO";
266   case VK_Mips_GOTTPREL: return "GOTTPREL";
267   case VK_Mips_TPREL_HI: return "TPREL_HI";
268   case VK_Mips_TPREL_LO: return "TPREL_LO";
269   case VK_Mips_GPOFF_HI: return "GPOFF_HI";
270   case VK_Mips_GPOFF_LO: return "GPOFF_LO";
271   case VK_Mips_GOT_DISP: return "GOT_DISP";
272   case VK_Mips_GOT_PAGE: return "GOT_PAGE";
273   case VK_Mips_GOT_OFST: return "GOT_OFST";
274   case VK_Mips_HIGHER:   return "HIGHER";
275   case VK_Mips_HIGHEST:  return "HIGHEST";
276   case VK_Mips_GOT_HI16: return "GOT_HI16";
277   case VK_Mips_GOT_LO16: return "GOT_LO16";
278   case VK_Mips_CALL_HI16: return "CALL_HI16";
279   case VK_Mips_CALL_LO16: return "CALL_LO16";
280   case VK_Mips_PCREL_HI16: return "PCREL_HI16";
281   case VK_Mips_PCREL_LO16: return "PCREL_LO16";
282   case VK_COFF_IMGREL32: return "IMGREL";
283   }
284   llvm_unreachable("Invalid variant kind");
285 }
286
287 MCSymbolRefExpr::VariantKind
288 MCSymbolRefExpr::getVariantKindForName(StringRef Name) {
289   return StringSwitch<VariantKind>(Name.lower())
290     .Case("got", VK_GOT)
291     .Case("gotoff", VK_GOTOFF)
292     .Case("gotpcrel", VK_GOTPCREL)
293     .Case("got_prel", VK_GOTPCREL)
294     .Case("gottpoff", VK_GOTTPOFF)
295     .Case("indntpoff", VK_INDNTPOFF)
296     .Case("ntpoff", VK_NTPOFF)
297     .Case("gotntpoff", VK_GOTNTPOFF)
298     .Case("plt", VK_PLT)
299     .Case("tlsgd", VK_TLSGD)
300     .Case("tlsld", VK_TLSLD)
301     .Case("tlsldm", VK_TLSLDM)
302     .Case("tpoff", VK_TPOFF)
303     .Case("dtpoff", VK_DTPOFF)
304     .Case("tlvp", VK_TLVP)
305     .Case("tlvppage", VK_TLVPPAGE)
306     .Case("tlvppageoff", VK_TLVPPAGEOFF)
307     .Case("page", VK_PAGE)
308     .Case("pageoff", VK_PAGEOFF)
309     .Case("gotpage", VK_GOTPAGE)
310     .Case("gotpageoff", VK_GOTPAGEOFF)
311     .Case("imgrel", VK_COFF_IMGREL32)
312     .Case("secrel32", VK_SECREL)
313     .Case("l", VK_PPC_LO)
314     .Case("h", VK_PPC_HI)
315     .Case("ha", VK_PPC_HA)
316     .Case("higher", VK_PPC_HIGHER)
317     .Case("highera", VK_PPC_HIGHERA)
318     .Case("highest", VK_PPC_HIGHEST)
319     .Case("highesta", VK_PPC_HIGHESTA)
320     .Case("got@l", VK_PPC_GOT_LO)
321     .Case("got@h", VK_PPC_GOT_HI)
322     .Case("got@ha", VK_PPC_GOT_HA)
323     .Case("local", VK_PPC_LOCAL)
324     .Case("tocbase", VK_PPC_TOCBASE)
325     .Case("toc", VK_PPC_TOC)
326     .Case("toc@l", VK_PPC_TOC_LO)
327     .Case("toc@h", VK_PPC_TOC_HI)
328     .Case("toc@ha", VK_PPC_TOC_HA)
329     .Case("tls", VK_PPC_TLS)
330     .Case("dtpmod", VK_PPC_DTPMOD)
331     .Case("tprel", VK_PPC_TPREL)
332     .Case("tprel@l", VK_PPC_TPREL_LO)
333     .Case("tprel@h", VK_PPC_TPREL_HI)
334     .Case("tprel@ha", VK_PPC_TPREL_HA)
335     .Case("tprel@higher", VK_PPC_TPREL_HIGHER)
336     .Case("tprel@highera", VK_PPC_TPREL_HIGHERA)
337     .Case("tprel@highest", VK_PPC_TPREL_HIGHEST)
338     .Case("tprel@highesta", VK_PPC_TPREL_HIGHESTA)
339     .Case("dtprel", VK_PPC_DTPREL)
340     .Case("dtprel@l", VK_PPC_DTPREL_LO)
341     .Case("dtprel@h", VK_PPC_DTPREL_HI)
342     .Case("dtprel@ha", VK_PPC_DTPREL_HA)
343     .Case("dtprel@higher", VK_PPC_DTPREL_HIGHER)
344     .Case("dtprel@highera", VK_PPC_DTPREL_HIGHERA)
345     .Case("dtprel@highest", VK_PPC_DTPREL_HIGHEST)
346     .Case("dtprel@highesta", VK_PPC_DTPREL_HIGHESTA)
347     .Case("got@tprel", VK_PPC_GOT_TPREL)
348     .Case("got@tprel@l", VK_PPC_GOT_TPREL_LO)
349     .Case("got@tprel@h", VK_PPC_GOT_TPREL_HI)
350     .Case("got@tprel@ha", VK_PPC_GOT_TPREL_HA)
351     .Case("got@dtprel", VK_PPC_GOT_DTPREL)
352     .Case("got@dtprel@l", VK_PPC_GOT_DTPREL_LO)
353     .Case("got@dtprel@h", VK_PPC_GOT_DTPREL_HI)
354     .Case("got@dtprel@ha", VK_PPC_GOT_DTPREL_HA)
355     .Case("got@tlsgd", VK_PPC_GOT_TLSGD)
356     .Case("got@tlsgd@l", VK_PPC_GOT_TLSGD_LO)
357     .Case("got@tlsgd@h", VK_PPC_GOT_TLSGD_HI)
358     .Case("got@tlsgd@ha", VK_PPC_GOT_TLSGD_HA)
359     .Case("got@tlsld", VK_PPC_GOT_TLSLD)
360     .Case("got@tlsld@l", VK_PPC_GOT_TLSLD_LO)
361     .Case("got@tlsld@h", VK_PPC_GOT_TLSLD_HI)
362     .Case("got@tlsld@ha", VK_PPC_GOT_TLSLD_HA)
363     .Case("none", VK_ARM_NONE)
364     .Case("target1", VK_ARM_TARGET1)
365     .Case("target2", VK_ARM_TARGET2)
366     .Case("prel31", VK_ARM_PREL31)
367     .Case("tlsldo", VK_ARM_TLSLDO)
368     .Case("tlscall", VK_ARM_TLSCALL)
369     .Case("tlsdesc", VK_ARM_TLSDESC)
370     .Default(VK_Invalid);
371 }
372
373 void MCSymbolRefExpr::printVariantKind(raw_ostream &OS) const {
374   if (UseParensForSymbolVariant)
375     OS << '(' << MCSymbolRefExpr::getVariantKindName(getKind()) << ')';
376   else
377     OS << '@' << MCSymbolRefExpr::getVariantKindName(getKind());
378 }
379
380 /* *** */
381
382 void MCTargetExpr::anchor() {}
383
384 /* *** */
385
386 bool MCExpr::EvaluateAsAbsolute(int64_t &Res) const {
387   return EvaluateAsAbsolute(Res, nullptr, nullptr, nullptr);
388 }
389
390 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
391                                 const MCAsmLayout &Layout) const {
392   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr);
393 }
394
395 bool MCExpr::EvaluateAsAbsolute(int64_t &Res,
396                                 const MCAsmLayout &Layout,
397                                 const SectionAddrMap &Addrs) const {
398   return EvaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, &Addrs);
399 }
400
401 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const {
402   return EvaluateAsAbsolute(Res, &Asm, nullptr, nullptr);
403 }
404
405 int64_t MCExpr::evaluateKnownAbsolute(const MCAsmLayout &Layout) const {
406   int64_t Res;
407   bool Abs =
408       evaluateAsAbsolute(Res, &Layout.getAssembler(), &Layout, nullptr, true);
409   (void)Abs;
410   assert(Abs && "Not actually absolute");
411   return Res;
412 }
413
414 bool MCExpr::EvaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
415                                 const MCAsmLayout *Layout,
416                                 const SectionAddrMap *Addrs) const {
417   // FIXME: The use if InSet = Addrs is a hack. Setting InSet causes us
418   // absolutize differences across sections and that is what the MachO writer
419   // uses Addrs for.
420   return evaluateAsAbsolute(Res, Asm, Layout, Addrs, Addrs);
421 }
422
423 bool MCExpr::evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
424                                 const MCAsmLayout *Layout,
425                                 const SectionAddrMap *Addrs, bool InSet) const {
426   MCValue Value;
427
428   // Fast path constants.
429   if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(this)) {
430     Res = CE->getValue();
431     return true;
432   }
433
434   bool IsRelocatable = EvaluateAsRelocatableImpl(
435       Value, Asm, Layout, nullptr, Addrs, InSet, /*ForceVarExpansion*/ false);
436
437   // Record the current value.
438   Res = Value.getConstant();
439
440   return IsRelocatable && Value.isAbsolute();
441 }
442
443 /// \brief Helper method for \see EvaluateSymbolAdd().
444 static void AttemptToFoldSymbolOffsetDifference(const MCAssembler *Asm,
445                                                 const MCAsmLayout *Layout,
446                                                 const SectionAddrMap *Addrs,
447                                                 bool InSet,
448                                                 const MCSymbolRefExpr *&A,
449                                                 const MCSymbolRefExpr *&B,
450                                                 int64_t &Addend) {
451   if (!A || !B)
452     return;
453
454   const MCSymbol &SA = A->getSymbol();
455   const MCSymbol &SB = B->getSymbol();
456
457   if (SA.isUndefined() || SB.isUndefined())
458     return;
459
460   if (!Asm->getWriter().IsSymbolRefDifferenceFullyResolved(*Asm, A, B, InSet))
461     return;
462
463   const MCSymbolData &AD = Asm->getSymbolData(SA);
464   const MCSymbolData &BD = Asm->getSymbolData(SB);
465
466   if (AD.getFragment() == BD.getFragment()) {
467     Addend += (AD.getOffset() - BD.getOffset());
468
469     // Pointers to Thumb symbols need to have their low-bit set to allow
470     // for interworking.
471     if (Asm->isThumbFunc(&SA))
472       Addend |= 1;
473
474     // Clear the symbol expr pointers to indicate we have folded these
475     // operands.
476     A = B = nullptr;
477     return;
478   }
479
480   if (!Layout)
481     return;
482
483   const MCSectionData &SecA = *AD.getFragment()->getParent();
484   const MCSectionData &SecB = *BD.getFragment()->getParent();
485
486   if ((&SecA != &SecB) && !Addrs)
487     return;
488
489   // Eagerly evaluate.
490   Addend += (Layout->getSymbolOffset(&Asm->getSymbolData(A->getSymbol())) -
491              Layout->getSymbolOffset(&Asm->getSymbolData(B->getSymbol())));
492   if (Addrs && (&SecA != &SecB))
493     Addend += (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
494
495   // Pointers to Thumb symbols need to have their low-bit set to allow
496   // for interworking.
497   if (Asm->isThumbFunc(&SA))
498     Addend |= 1;
499
500   // Clear the symbol expr pointers to indicate we have folded these
501   // operands.
502   A = B = nullptr;
503 }
504
505 /// \brief Evaluate the result of an add between (conceptually) two MCValues.
506 ///
507 /// This routine conceptually attempts to construct an MCValue:
508 ///   Result = (Result_A - Result_B + Result_Cst)
509 /// from two MCValue's LHS and RHS where
510 ///   Result = LHS + RHS
511 /// and
512 ///   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
513 ///
514 /// This routine attempts to aggresively fold the operands such that the result
515 /// is representable in an MCValue, but may not always succeed.
516 ///
517 /// \returns True on success, false if the result is not representable in an
518 /// MCValue.
519
520 /// NOTE: It is really important to have both the Asm and Layout arguments.
521 /// They might look redundant, but this function can be used before layout
522 /// is done (see the object streamer for example) and having the Asm argument
523 /// lets us avoid relaxations early.
524 static bool EvaluateSymbolicAdd(const MCAssembler *Asm,
525                                 const MCAsmLayout *Layout,
526                                 const SectionAddrMap *Addrs,
527                                 bool InSet,
528                                 const MCValue &LHS,const MCSymbolRefExpr *RHS_A,
529                                 const MCSymbolRefExpr *RHS_B, int64_t RHS_Cst,
530                                 MCValue &Res) {
531   // FIXME: This routine (and other evaluation parts) are *incredibly* sloppy
532   // about dealing with modifiers. This will ultimately bite us, one day.
533   const MCSymbolRefExpr *LHS_A = LHS.getSymA();
534   const MCSymbolRefExpr *LHS_B = LHS.getSymB();
535   int64_t LHS_Cst = LHS.getConstant();
536
537   // Fold the result constant immediately.
538   int64_t Result_Cst = LHS_Cst + RHS_Cst;
539
540   assert((!Layout || Asm) &&
541          "Must have an assembler object if layout is given!");
542
543   // If we have a layout, we can fold resolved differences.
544   if (Asm) {
545     // First, fold out any differences which are fully resolved. By
546     // reassociating terms in
547     //   Result = (LHS_A - LHS_B + LHS_Cst) + (RHS_A - RHS_B + RHS_Cst).
548     // we have the four possible differences:
549     //   (LHS_A - LHS_B),
550     //   (LHS_A - RHS_B),
551     //   (RHS_A - LHS_B),
552     //   (RHS_A - RHS_B).
553     // Since we are attempting to be as aggressive as possible about folding, we
554     // attempt to evaluate each possible alternative.
555     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, LHS_B,
556                                         Result_Cst);
557     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, LHS_A, RHS_B,
558                                         Result_Cst);
559     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, LHS_B,
560                                         Result_Cst);
561     AttemptToFoldSymbolOffsetDifference(Asm, Layout, Addrs, InSet, RHS_A, RHS_B,
562                                         Result_Cst);
563   }
564
565   // We can't represent the addition or subtraction of two symbols.
566   if ((LHS_A && RHS_A) || (LHS_B && RHS_B))
567     return false;
568
569   // At this point, we have at most one additive symbol and one subtractive
570   // symbol -- find them.
571   const MCSymbolRefExpr *A = LHS_A ? LHS_A : RHS_A;
572   const MCSymbolRefExpr *B = LHS_B ? LHS_B : RHS_B;
573
574   // If we have a negated symbol, then we must have also have a non-negated
575   // symbol in order to encode the expression.
576   if (B && !A)
577     return false;
578
579   Res = MCValue::get(A, B, Result_Cst);
580   return true;
581 }
582
583 bool MCExpr::EvaluateAsRelocatable(MCValue &Res,
584                                    const MCAsmLayout *Layout,
585                                    const MCFixup *Fixup) const {
586   MCAssembler *Assembler = Layout ? &Layout->getAssembler() : nullptr;
587   return EvaluateAsRelocatableImpl(Res, Assembler, Layout, Fixup, nullptr,
588                                    false, /*ForceVarExpansion*/ false);
589 }
590
591 bool MCExpr::EvaluateAsValue(MCValue &Res, const MCAsmLayout *Layout,
592                              const MCFixup *Fixup) const {
593   MCAssembler *Assembler = Layout ? &Layout->getAssembler() : nullptr;
594   return EvaluateAsRelocatableImpl(Res, Assembler, Layout, Fixup, nullptr,
595                                    false, /*ForceVarExpansion*/ true);
596 }
597
598 bool MCExpr::EvaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,
599                                        const MCAsmLayout *Layout,
600                                        const MCFixup *Fixup,
601                                        const SectionAddrMap *Addrs, bool InSet,
602                                        bool ForceVarExpansion) const {
603   ++stats::MCExprEvaluate;
604
605   switch (getKind()) {
606   case Target:
607     return cast<MCTargetExpr>(this)->EvaluateAsRelocatableImpl(Res, Layout,
608                                                                Fixup);
609
610   case Constant:
611     Res = MCValue::get(cast<MCConstantExpr>(this)->getValue());
612     return true;
613
614   case SymbolRef: {
615     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
616     const MCSymbol &Sym = SRE->getSymbol();
617
618     // Evaluate recursively if this is a variable.
619     if (Sym.isVariable() && SRE->getKind() == MCSymbolRefExpr::VK_None) {
620       if (Sym.getVariableValue()->EvaluateAsRelocatableImpl(
621               Res, Asm, Layout, Fixup, Addrs, true, ForceVarExpansion)) {
622         const MCSymbolRefExpr *A = Res.getSymA();
623         const MCSymbolRefExpr *B = Res.getSymB();
624
625         if (SRE->hasSubsectionsViaSymbols()) {
626           // FIXME: This is small hack. Given
627           // a = b + 4
628           // .long a
629           // the OS X assembler will completely drop the 4. We should probably
630           // include it in the relocation or produce an error if that is not
631           // possible.
632           if (!A && !B)
633             return true;
634         } else {
635           if (ForceVarExpansion)
636             return true;
637           bool IsSymbol = A && A->getSymbol().isDefined();
638           if (!IsSymbol)
639             return true;
640         }
641       }
642     }
643
644     Res = MCValue::get(SRE, nullptr, 0);
645     return true;
646   }
647
648   case Unary: {
649     const MCUnaryExpr *AUE = cast<MCUnaryExpr>(this);
650     MCValue Value;
651
652     if (!AUE->getSubExpr()->EvaluateAsRelocatableImpl(Value, Asm, Layout,
653                                                       Fixup, Addrs, InSet,
654                                                       ForceVarExpansion))
655       return false;
656
657     switch (AUE->getOpcode()) {
658     case MCUnaryExpr::LNot:
659       if (!Value.isAbsolute())
660         return false;
661       Res = MCValue::get(!Value.getConstant());
662       break;
663     case MCUnaryExpr::Minus:
664       /// -(a - b + const) ==> (b - a - const)
665       if (Value.getSymA() && !Value.getSymB())
666         return false;
667       Res = MCValue::get(Value.getSymB(), Value.getSymA(),
668                          -Value.getConstant());
669       break;
670     case MCUnaryExpr::Not:
671       if (!Value.isAbsolute())
672         return false;
673       Res = MCValue::get(~Value.getConstant());
674       break;
675     case MCUnaryExpr::Plus:
676       Res = Value;
677       break;
678     }
679
680     return true;
681   }
682
683   case Binary: {
684     const MCBinaryExpr *ABE = cast<MCBinaryExpr>(this);
685     MCValue LHSValue, RHSValue;
686
687     if (!ABE->getLHS()->EvaluateAsRelocatableImpl(LHSValue, Asm, Layout,
688                                                   Fixup, Addrs, InSet,
689                                                   ForceVarExpansion) ||
690         !ABE->getRHS()->EvaluateAsRelocatableImpl(RHSValue, Asm, Layout,
691                                                   Fixup, Addrs, InSet,
692                                                   ForceVarExpansion))
693       return false;
694
695     // We only support a few operations on non-constant expressions, handle
696     // those first.
697     if (!LHSValue.isAbsolute() || !RHSValue.isAbsolute()) {
698       switch (ABE->getOpcode()) {
699       default:
700         return false;
701       case MCBinaryExpr::Sub:
702         // Negate RHS and add.
703         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
704                                    RHSValue.getSymB(), RHSValue.getSymA(),
705                                    -RHSValue.getConstant(),
706                                    Res);
707
708       case MCBinaryExpr::Add:
709         return EvaluateSymbolicAdd(Asm, Layout, Addrs, InSet, LHSValue,
710                                    RHSValue.getSymA(), RHSValue.getSymB(),
711                                    RHSValue.getConstant(),
712                                    Res);
713       }
714     }
715
716     // FIXME: We need target hooks for the evaluation. It may be limited in
717     // width, and gas defines the result of comparisons and right shifts
718     // differently from Apple as.
719     int64_t LHS = LHSValue.getConstant(), RHS = RHSValue.getConstant();
720     int64_t Result = 0;
721     switch (ABE->getOpcode()) {
722     case MCBinaryExpr::Add:  Result = LHS + RHS; break;
723     case MCBinaryExpr::And:  Result = LHS & RHS; break;
724     case MCBinaryExpr::Div:  Result = LHS / RHS; break;
725     case MCBinaryExpr::EQ:   Result = LHS == RHS; break;
726     case MCBinaryExpr::GT:   Result = LHS > RHS; break;
727     case MCBinaryExpr::GTE:  Result = LHS >= RHS; break;
728     case MCBinaryExpr::LAnd: Result = LHS && RHS; break;
729     case MCBinaryExpr::LOr:  Result = LHS || RHS; break;
730     case MCBinaryExpr::LT:   Result = LHS < RHS; break;
731     case MCBinaryExpr::LTE:  Result = LHS <= RHS; break;
732     case MCBinaryExpr::Mod:  Result = LHS % RHS; break;
733     case MCBinaryExpr::Mul:  Result = LHS * RHS; break;
734     case MCBinaryExpr::NE:   Result = LHS != RHS; break;
735     case MCBinaryExpr::Or:   Result = LHS | RHS; break;
736     case MCBinaryExpr::Shl:  Result = LHS << RHS; break;
737     case MCBinaryExpr::Shr:  Result = LHS >> RHS; break;
738     case MCBinaryExpr::Sub:  Result = LHS - RHS; break;
739     case MCBinaryExpr::Xor:  Result = LHS ^ RHS; break;
740     }
741
742     Res = MCValue::get(Result);
743     return true;
744   }
745   }
746
747   llvm_unreachable("Invalid assembly expression kind!");
748 }
749
750 const MCSection *MCExpr::FindAssociatedSection() const {
751   switch (getKind()) {
752   case Target:
753     // We never look through target specific expressions.
754     return cast<MCTargetExpr>(this)->FindAssociatedSection();
755
756   case Constant:
757     return MCSymbol::AbsolutePseudoSection;
758
759   case SymbolRef: {
760     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(this);
761     const MCSymbol &Sym = SRE->getSymbol();
762
763     if (Sym.isDefined())
764       return &Sym.getSection();
765
766     return nullptr;
767   }
768
769   case Unary:
770     return cast<MCUnaryExpr>(this)->getSubExpr()->FindAssociatedSection();
771
772   case Binary: {
773     const MCBinaryExpr *BE = cast<MCBinaryExpr>(this);
774     const MCSection *LHS_S = BE->getLHS()->FindAssociatedSection();
775     const MCSection *RHS_S = BE->getRHS()->FindAssociatedSection();
776
777     // If either section is absolute, return the other.
778     if (LHS_S == MCSymbol::AbsolutePseudoSection)
779       return RHS_S;
780     if (RHS_S == MCSymbol::AbsolutePseudoSection)
781       return LHS_S;
782
783     // Otherwise, return the first non-null section.
784     return LHS_S ? LHS_S : RHS_S;
785   }
786   }
787
788   llvm_unreachable("Invalid assembly expression kind!");
789 }