Add a new function attribute 'cold' to functions.
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attributes.cpp - Implement AttributesList -------------------------===//
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 // \file
11 // \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeSetImpl, and AttributeSet classes.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/Support/Atomic.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Attribute Construction Methods
31 //===----------------------------------------------------------------------===//
32
33 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
34                          uint64_t Val) {
35   LLVMContextImpl *pImpl = Context.pImpl;
36   FoldingSetNodeID ID;
37   ID.AddInteger(Kind);
38   if (Val) ID.AddInteger(Val);
39
40   void *InsertPoint;
41   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
42
43   if (!PA) {
44     // If we didn't find any existing attributes of the same shape then create a
45     // new one and insert it.
46     PA = !Val ?
47       new AttributeImpl(Context, Kind) :
48       new AttributeImpl(Context, Kind, Val);
49     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
50   }
51
52   // Return the Attribute that we found or created.
53   return Attribute(PA);
54 }
55
56 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
57   LLVMContextImpl *pImpl = Context.pImpl;
58   FoldingSetNodeID ID;
59   ID.AddString(Kind);
60   if (!Val.empty()) ID.AddString(Val);
61
62   void *InsertPoint;
63   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
64
65   if (!PA) {
66     // If we didn't find any existing attributes of the same shape then create a
67     // new one and insert it.
68     PA = new AttributeImpl(Context, Kind, Val);
69     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
70   }
71
72   // Return the Attribute that we found or created.
73   return Attribute(PA);
74 }
75
76 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
77   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
78   assert(Align <= 0x40000000 && "Alignment too large.");
79   return get(Context, Alignment, Align);
80 }
81
82 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
83                                            uint64_t Align) {
84   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
85   assert(Align <= 0x100 && "Alignment too large.");
86   return get(Context, StackAlignment, Align);
87 }
88
89 //===----------------------------------------------------------------------===//
90 // Attribute Accessor Methods
91 //===----------------------------------------------------------------------===//
92
93 bool Attribute::isEnumAttribute() const {
94   return pImpl && pImpl->isEnumAttribute();
95 }
96
97 bool Attribute::isAlignAttribute() const {
98   return pImpl && pImpl->isAlignAttribute();
99 }
100
101 bool Attribute::isStringAttribute() const {
102   return pImpl && pImpl->isStringAttribute();
103 }
104
105 Attribute::AttrKind Attribute::getKindAsEnum() const {
106   assert((isEnumAttribute() || isAlignAttribute()) &&
107          "Invalid attribute type to get the kind as an enum!");
108   return pImpl ? pImpl->getKindAsEnum() : None;
109 }
110
111 uint64_t Attribute::getValueAsInt() const {
112   assert(isAlignAttribute() &&
113          "Expected the attribute to be an alignment attribute!");
114   return pImpl ? pImpl->getValueAsInt() : 0;
115 }
116
117 StringRef Attribute::getKindAsString() const {
118   assert(isStringAttribute() &&
119          "Invalid attribute type to get the kind as a string!");
120   return pImpl ? pImpl->getKindAsString() : StringRef();
121 }
122
123 StringRef Attribute::getValueAsString() const {
124   assert(isStringAttribute() &&
125          "Invalid attribute type to get the value as a string!");
126   return pImpl ? pImpl->getValueAsString() : StringRef();
127 }
128
129 bool Attribute::hasAttribute(AttrKind Kind) const {
130   return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
131 }
132
133 bool Attribute::hasAttribute(StringRef Kind) const {
134   if (!isStringAttribute()) return false;
135   return pImpl && pImpl->hasAttribute(Kind);
136 }
137
138 /// This returns the alignment field of an attribute as a byte alignment value.
139 unsigned Attribute::getAlignment() const {
140   assert(hasAttribute(Attribute::Alignment) &&
141          "Trying to get alignment from non-alignment attribute!");
142   return pImpl->getValueAsInt();
143 }
144
145 /// This returns the stack alignment field of an attribute as a byte alignment
146 /// value.
147 unsigned Attribute::getStackAlignment() const {
148   assert(hasAttribute(Attribute::StackAlignment) &&
149          "Trying to get alignment from non-alignment attribute!");
150   return pImpl->getValueAsInt();
151 }
152
153 std::string Attribute::getAsString(bool InAttrGrp) const {
154   if (!pImpl) return "";
155
156   if (hasAttribute(Attribute::SanitizeAddress))
157     return "sanitize_address";
158   if (hasAttribute(Attribute::AlwaysInline))
159     return "alwaysinline";
160   if (hasAttribute(Attribute::ByVal))
161     return "byval";
162   if (hasAttribute(Attribute::InlineHint))
163     return "inlinehint";
164   if (hasAttribute(Attribute::InReg))
165     return "inreg";
166   if (hasAttribute(Attribute::MinSize))
167     return "minsize";
168   if (hasAttribute(Attribute::Naked))
169     return "naked";
170   if (hasAttribute(Attribute::Nest))
171     return "nest";
172   if (hasAttribute(Attribute::NoAlias))
173     return "noalias";
174   if (hasAttribute(Attribute::NoBuiltin))
175     return "nobuiltin";
176   if (hasAttribute(Attribute::NoCapture))
177     return "nocapture";
178   if (hasAttribute(Attribute::NoDuplicate))
179     return "noduplicate";
180   if (hasAttribute(Attribute::NoImplicitFloat))
181     return "noimplicitfloat";
182   if (hasAttribute(Attribute::NoInline))
183     return "noinline";
184   if (hasAttribute(Attribute::NonLazyBind))
185     return "nonlazybind";
186   if (hasAttribute(Attribute::NoRedZone))
187     return "noredzone";
188   if (hasAttribute(Attribute::NoReturn))
189     return "noreturn";
190   if (hasAttribute(Attribute::NoUnwind))
191     return "nounwind";
192   if (hasAttribute(Attribute::OptimizeForSize))
193     return "optsize";
194   if (hasAttribute(Attribute::ReadNone))
195     return "readnone";
196   if (hasAttribute(Attribute::ReadOnly))
197     return "readonly";
198   if (hasAttribute(Attribute::Returned))
199     return "returned";
200   if (hasAttribute(Attribute::ReturnsTwice))
201     return "returns_twice";
202   if (hasAttribute(Attribute::SExt))
203     return "signext";
204   if (hasAttribute(Attribute::StackProtect))
205     return "ssp";
206   if (hasAttribute(Attribute::StackProtectReq))
207     return "sspreq";
208   if (hasAttribute(Attribute::StackProtectStrong))
209     return "sspstrong";
210   if (hasAttribute(Attribute::StructRet))
211     return "sret";
212   if (hasAttribute(Attribute::SanitizeThread))
213     return "sanitize_thread";
214   if (hasAttribute(Attribute::SanitizeMemory))
215     return "sanitize_memory";
216   if (hasAttribute(Attribute::UWTable))
217     return "uwtable";
218   if (hasAttribute(Attribute::ZExt))
219     return "zeroext";
220   if (hasAttribute(Attribute::Cold))
221     return "cold";
222
223   // FIXME: These should be output like this:
224   //
225   //   align=4
226   //   alignstack=8
227   //
228   if (hasAttribute(Attribute::Alignment)) {
229     std::string Result;
230     Result += "align";
231     Result += (InAttrGrp) ? "=" : " ";
232     Result += utostr(getValueAsInt());
233     return Result;
234   }
235
236   if (hasAttribute(Attribute::StackAlignment)) {
237     std::string Result;
238     Result += "alignstack";
239     if (InAttrGrp) {
240       Result += "=";
241       Result += utostr(getValueAsInt());
242     } else {
243       Result += "(";
244       Result += utostr(getValueAsInt());
245       Result += ")";
246     }
247     return Result;
248   }
249
250   // Convert target-dependent attributes to strings of the form:
251   //
252   //   "kind"
253   //   "kind" = "value"
254   //
255   if (isStringAttribute()) {
256     std::string Result;
257     Result += '\"' + getKindAsString().str() + '"';
258
259     StringRef Val = pImpl->getValueAsString();
260     if (Val.empty()) return Result;
261
262     Result += "=\"" + Val.str() + '"';
263     return Result;
264   }
265
266   llvm_unreachable("Unknown attribute");
267 }
268
269 bool Attribute::operator<(Attribute A) const {
270   if (!pImpl && !A.pImpl) return false;
271   if (!pImpl) return true;
272   if (!A.pImpl) return false;
273   return *pImpl < *A.pImpl;
274 }
275
276 //===----------------------------------------------------------------------===//
277 // AttributeImpl Definition
278 //===----------------------------------------------------------------------===//
279
280 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind Kind)
281   : Context(C), Entry(new EnumAttributeEntry(Kind)) {}
282
283 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind Kind,
284                              unsigned Align)
285   : Context(C) {
286   assert((Kind == Attribute::Alignment || Kind == Attribute::StackAlignment) &&
287          "Wrong kind for alignment attribute!");
288   Entry = new AlignAttributeEntry(Kind, Align);
289 }
290
291 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef Kind, StringRef Val)
292   : Context(C), Entry(new StringAttributeEntry(Kind, Val)) {}
293
294 AttributeImpl::~AttributeImpl() {
295   delete Entry;
296 }
297
298 bool AttributeImpl::isEnumAttribute() const {
299   return isa<EnumAttributeEntry>(Entry);
300 }
301
302 bool AttributeImpl::isAlignAttribute() const {
303   return isa<AlignAttributeEntry>(Entry);
304 }
305
306 bool AttributeImpl::isStringAttribute() const {
307   return isa<StringAttributeEntry>(Entry);
308 }
309
310 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
311   if (isStringAttribute()) return false;
312   return getKindAsEnum() == A;
313 }
314
315 bool AttributeImpl::hasAttribute(StringRef Kind) const {
316   if (!isStringAttribute()) return false;
317   return getKindAsString() == Kind;
318 }
319
320 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
321   if (EnumAttributeEntry *E = dyn_cast<EnumAttributeEntry>(Entry))
322     return E->getEnumKind();
323   return cast<AlignAttributeEntry>(Entry)->getEnumKind();
324 }
325
326 uint64_t AttributeImpl::getValueAsInt() const {
327   return cast<AlignAttributeEntry>(Entry)->getAlignment();
328 }
329
330 StringRef AttributeImpl::getKindAsString() const {
331   return cast<StringAttributeEntry>(Entry)->getStringKind();
332 }
333
334 StringRef AttributeImpl::getValueAsString() const {
335   return cast<StringAttributeEntry>(Entry)->getStringValue();
336 }
337
338 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
339   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
340   // relative to their enum value) and then strings.
341   if (isEnumAttribute()) {
342     if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
343     if (AI.isAlignAttribute()) return true;
344     if (AI.isStringAttribute()) return true;
345   }
346
347   if (isAlignAttribute()) {
348     if (AI.isEnumAttribute()) return false;
349     if (AI.isAlignAttribute()) return getValueAsInt() < AI.getValueAsInt();
350     if (AI.isStringAttribute()) return true;
351   }
352
353   if (AI.isEnumAttribute()) return false;
354   if (AI.isAlignAttribute()) return false;
355   if (getKindAsString() == AI.getKindAsString())
356     return getValueAsString() < AI.getValueAsString();
357   return getKindAsString() < AI.getKindAsString();
358 }
359
360 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
361   // FIXME: Remove this.
362   switch (Val) {
363   case Attribute::EndAttrKinds:
364     llvm_unreachable("Synthetic enumerators which should never get here");
365
366   case Attribute::None:            return 0;
367   case Attribute::ZExt:            return 1 << 0;
368   case Attribute::SExt:            return 1 << 1;
369   case Attribute::NoReturn:        return 1 << 2;
370   case Attribute::InReg:           return 1 << 3;
371   case Attribute::StructRet:       return 1 << 4;
372   case Attribute::NoUnwind:        return 1 << 5;
373   case Attribute::NoAlias:         return 1 << 6;
374   case Attribute::ByVal:           return 1 << 7;
375   case Attribute::Nest:            return 1 << 8;
376   case Attribute::ReadNone:        return 1 << 9;
377   case Attribute::ReadOnly:        return 1 << 10;
378   case Attribute::NoInline:        return 1 << 11;
379   case Attribute::AlwaysInline:    return 1 << 12;
380   case Attribute::OptimizeForSize: return 1 << 13;
381   case Attribute::StackProtect:    return 1 << 14;
382   case Attribute::StackProtectReq: return 1 << 15;
383   case Attribute::Alignment:       return 31 << 16;
384   case Attribute::NoCapture:       return 1 << 21;
385   case Attribute::NoRedZone:       return 1 << 22;
386   case Attribute::NoImplicitFloat: return 1 << 23;
387   case Attribute::Naked:           return 1 << 24;
388   case Attribute::InlineHint:      return 1 << 25;
389   case Attribute::StackAlignment:  return 7 << 26;
390   case Attribute::ReturnsTwice:    return 1 << 29;
391   case Attribute::UWTable:         return 1 << 30;
392   case Attribute::NonLazyBind:     return 1U << 31;
393   case Attribute::SanitizeAddress: return 1ULL << 32;
394   case Attribute::MinSize:         return 1ULL << 33;
395   case Attribute::NoDuplicate:     return 1ULL << 34;
396   case Attribute::StackProtectStrong: return 1ULL << 35;
397   case Attribute::SanitizeThread:  return 1ULL << 36;
398   case Attribute::SanitizeMemory:  return 1ULL << 37;
399   case Attribute::NoBuiltin:       return 1ULL << 38;
400   case Attribute::Returned:        return 1ULL << 39;
401   case Attribute::Cold:            return 1ULL << 40;
402   }
403   llvm_unreachable("Unsupported attribute type");
404 }
405
406 //===----------------------------------------------------------------------===//
407 // AttributeSetNode Definition
408 //===----------------------------------------------------------------------===//
409
410 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
411                                         ArrayRef<Attribute> Attrs) {
412   if (Attrs.empty())
413     return 0;
414
415   // Otherwise, build a key to look up the existing attributes.
416   LLVMContextImpl *pImpl = C.pImpl;
417   FoldingSetNodeID ID;
418
419   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
420   array_pod_sort(SortedAttrs.begin(), SortedAttrs.end());
421
422   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
423          E = SortedAttrs.end(); I != E; ++I)
424     I->Profile(ID);
425
426   void *InsertPoint;
427   AttributeSetNode *PA =
428     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
429
430   // If we didn't find any existing attributes of the same shape then create a
431   // new one and insert it.
432   if (!PA) {
433     PA = new AttributeSetNode(SortedAttrs);
434     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
435   }
436
437   // Return the AttributesListNode that we found or created.
438   return PA;
439 }
440
441 bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
442   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
443          E = AttrList.end(); I != E; ++I)
444     if (I->hasAttribute(Kind))
445       return true;
446   return false;
447 }
448
449 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
450   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
451          E = AttrList.end(); I != E; ++I)
452     if (I->hasAttribute(Kind))
453       return true;
454   return false;
455 }
456
457 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
458   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
459          E = AttrList.end(); I != E; ++I)
460     if (I->hasAttribute(Kind))
461       return *I;
462   return Attribute();
463 }
464
465 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
466   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
467          E = AttrList.end(); I != E; ++I)
468     if (I->hasAttribute(Kind))
469       return *I;
470   return Attribute();
471 }
472
473 unsigned AttributeSetNode::getAlignment() const {
474   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
475          E = AttrList.end(); I != E; ++I)
476     if (I->hasAttribute(Attribute::Alignment))
477       return I->getAlignment();
478   return 0;
479 }
480
481 unsigned AttributeSetNode::getStackAlignment() const {
482   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
483          E = AttrList.end(); I != E; ++I)
484     if (I->hasAttribute(Attribute::StackAlignment))
485       return I->getStackAlignment();
486   return 0;
487 }
488
489 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
490   std::string Str;
491   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
492          E = AttrList.end(); I != E; ++I) {
493     if (I != AttrList.begin())
494       Str += ' ';
495     Str += I->getAsString(InAttrGrp);
496   }
497   return Str;
498 }
499
500 //===----------------------------------------------------------------------===//
501 // AttributeSetImpl Definition
502 //===----------------------------------------------------------------------===//
503
504 uint64_t AttributeSetImpl::Raw(unsigned Index) const {
505   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
506     if (getSlotIndex(I) != Index) continue;
507     const AttributeSetNode *ASN = AttrNodes[I].second;
508     uint64_t Mask = 0;
509
510     for (AttributeSetNode::const_iterator II = ASN->begin(),
511            IE = ASN->end(); II != IE; ++II) {
512       Attribute Attr = *II;
513
514       // This cannot handle string attributes.
515       if (Attr.isStringAttribute()) continue;
516
517       Attribute::AttrKind Kind = Attr.getKindAsEnum();
518
519       if (Kind == Attribute::Alignment)
520         Mask |= (Log2_32(ASN->getAlignment()) + 1) << 16;
521       else if (Kind == Attribute::StackAlignment)
522         Mask |= (Log2_32(ASN->getStackAlignment()) + 1) << 26;
523       else
524         Mask |= AttributeImpl::getAttrMask(Kind);
525     }
526
527     return Mask;
528   }
529
530   return 0;
531 }
532
533 //===----------------------------------------------------------------------===//
534 // AttributeSet Construction and Mutation Methods
535 //===----------------------------------------------------------------------===//
536
537 AttributeSet
538 AttributeSet::getImpl(LLVMContext &C,
539                       ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
540   LLVMContextImpl *pImpl = C.pImpl;
541   FoldingSetNodeID ID;
542   AttributeSetImpl::Profile(ID, Attrs);
543
544   void *InsertPoint;
545   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
546
547   // If we didn't find any existing attributes of the same shape then
548   // create a new one and insert it.
549   if (!PA) {
550     PA = new AttributeSetImpl(C, Attrs);
551     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
552   }
553
554   // Return the AttributesList that we found or created.
555   return AttributeSet(PA);
556 }
557
558 AttributeSet AttributeSet::get(LLVMContext &C,
559                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
560   // If there are no attributes then return a null AttributesList pointer.
561   if (Attrs.empty())
562     return AttributeSet();
563
564 #ifndef NDEBUG
565   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
566     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
567            "Misordered Attributes list!");
568     assert(!Attrs[i].second.hasAttribute(Attribute::None) &&
569            "Pointless attribute!");
570   }
571 #endif
572
573   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
574   // list.
575   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
576   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
577          E = Attrs.end(); I != E; ) {
578     unsigned Index = I->first;
579     SmallVector<Attribute, 4> AttrVec;
580     while (I != E && I->first == Index) {
581       AttrVec.push_back(I->second);
582       ++I;
583     }
584
585     AttrPairVec.push_back(std::make_pair(Index,
586                                          AttributeSetNode::get(C, AttrVec)));
587   }
588
589   return getImpl(C, AttrPairVec);
590 }
591
592 AttributeSet AttributeSet::get(LLVMContext &C,
593                                ArrayRef<std::pair<unsigned,
594                                                   AttributeSetNode*> > Attrs) {
595   // If there are no attributes then return a null AttributesList pointer.
596   if (Attrs.empty())
597     return AttributeSet();
598
599   return getImpl(C, Attrs);
600 }
601
602 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index, AttrBuilder &B) {
603   if (!B.hasAttributes())
604     return AttributeSet();
605
606   // Add target-independent attributes.
607   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
608   for (Attribute::AttrKind Kind = Attribute::None;
609        Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
610     if (!B.contains(Kind))
611       continue;
612
613     if (Kind == Attribute::Alignment)
614       Attrs.push_back(std::make_pair(Index, Attribute::
615                                      getWithAlignment(C, B.getAlignment())));
616     else if (Kind == Attribute::StackAlignment)
617       Attrs.push_back(std::make_pair(Index, Attribute::
618                               getWithStackAlignment(C, B.getStackAlignment())));
619     else
620       Attrs.push_back(std::make_pair(Index, Attribute::get(C, Kind)));
621   }
622
623   // Add target-dependent (string) attributes.
624   for (AttrBuilder::td_iterator I = B.td_begin(), E = B.td_end();
625        I != E; ++I)
626     Attrs.push_back(std::make_pair(Index, Attribute::get(C, I->first,I->second)));
627
628   return get(C, Attrs);
629 }
630
631 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index,
632                                ArrayRef<Attribute::AttrKind> Kind) {
633   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
634   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
635          E = Kind.end(); I != E; ++I)
636     Attrs.push_back(std::make_pair(Index, Attribute::get(C, *I)));
637   return get(C, Attrs);
638 }
639
640 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
641   if (Attrs.empty()) return AttributeSet();
642
643   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
644   for (unsigned I = 0, E = Attrs.size(); I != E; ++I) {
645     AttributeSet AS = Attrs[I];
646     if (!AS.pImpl) continue;
647     AttrNodeVec.append(AS.pImpl->AttrNodes.begin(), AS.pImpl->AttrNodes.end());
648   }
649
650   return getImpl(C, AttrNodeVec);
651 }
652
653 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
654                                         Attribute::AttrKind Attr) const {
655   if (hasAttribute(Index, Attr)) return *this;
656   return addAttributes(C, Index, AttributeSet::get(C, Index, Attr));
657 }
658
659 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
660                                         StringRef Kind) const {
661   llvm::AttrBuilder B;
662   B.addAttribute(Kind);
663   return addAttributes(C, Index, AttributeSet::get(C, Index, B));
664 }
665
666 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Index,
667                                          AttributeSet Attrs) const {
668   if (!pImpl) return Attrs;
669   if (!Attrs.pImpl) return *this;
670
671 #ifndef NDEBUG
672   // FIXME it is not obvious how this should work for alignment. For now, say
673   // we can't change a known alignment.
674   unsigned OldAlign = getParamAlignment(Index);
675   unsigned NewAlign = Attrs.getParamAlignment(Index);
676   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
677          "Attempt to change alignment!");
678 #endif
679
680   // Add the attribute slots before the one we're trying to add.
681   SmallVector<AttributeSet, 4> AttrSet;
682   uint64_t NumAttrs = pImpl->getNumAttributes();
683   AttributeSet AS;
684   uint64_t LastIndex = 0;
685   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
686     if (getSlotIndex(I) >= Index) {
687       if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
688       break;
689     }
690     LastIndex = I + 1;
691     AttrSet.push_back(getSlotAttributes(I));
692   }
693
694   // Now add the attribute into the correct slot. There may already be an
695   // AttributeSet there.
696   AttrBuilder B(AS, Index);
697
698   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
699     if (Attrs.getSlotIndex(I) == Index) {
700       for (AttributeSetImpl::const_iterator II = Attrs.pImpl->begin(I),
701              IE = Attrs.pImpl->end(I); II != IE; ++II)
702         B.addAttribute(*II);
703       break;
704     }
705
706   AttrSet.push_back(AttributeSet::get(C, Index, B));
707
708   // Add the remaining attribute slots.
709   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
710     AttrSet.push_back(getSlotAttributes(I));
711
712   return get(C, AttrSet);
713 }
714
715 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Index,
716                                            Attribute::AttrKind Attr) const {
717   if (!hasAttribute(Index, Attr)) return *this;
718   return removeAttributes(C, Index, AttributeSet::get(C, Index, Attr));
719 }
720
721 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Index,
722                                             AttributeSet Attrs) const {
723   if (!pImpl) return AttributeSet();
724   if (!Attrs.pImpl) return *this;
725
726 #ifndef NDEBUG
727   // FIXME it is not obvious how this should work for alignment.
728   // For now, say we can't pass in alignment, which no current use does.
729   assert(!Attrs.hasAttribute(Index, Attribute::Alignment) &&
730          "Attempt to change alignment!");
731 #endif
732
733   // Add the attribute slots before the one we're trying to add.
734   SmallVector<AttributeSet, 4> AttrSet;
735   uint64_t NumAttrs = pImpl->getNumAttributes();
736   AttributeSet AS;
737   uint64_t LastIndex = 0;
738   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
739     if (getSlotIndex(I) >= Index) {
740       if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
741       break;
742     }
743     LastIndex = I + 1;
744     AttrSet.push_back(getSlotAttributes(I));
745   }
746
747   // Now remove the attribute from the correct slot. There may already be an
748   // AttributeSet there.
749   AttrBuilder B(AS, Index);
750
751   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
752     if (Attrs.getSlotIndex(I) == Index) {
753       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Index);
754       break;
755     }
756
757   AttrSet.push_back(AttributeSet::get(C, Index, B));
758
759   // Add the remaining attribute slots.
760   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
761     AttrSet.push_back(getSlotAttributes(I));
762
763   return get(C, AttrSet);
764 }
765
766 //===----------------------------------------------------------------------===//
767 // AttributeSet Accessor Methods
768 //===----------------------------------------------------------------------===//
769
770 LLVMContext &AttributeSet::getContext() const {
771   return pImpl->getContext();
772 }
773
774 AttributeSet AttributeSet::getParamAttributes(unsigned Index) const {
775   return pImpl && hasAttributes(Index) ?
776     AttributeSet::get(pImpl->getContext(),
777                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
778                         std::make_pair(Index, getAttributes(Index)))) :
779     AttributeSet();
780 }
781
782 AttributeSet AttributeSet::getRetAttributes() const {
783   return pImpl && hasAttributes(ReturnIndex) ?
784     AttributeSet::get(pImpl->getContext(),
785                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
786                         std::make_pair(ReturnIndex,
787                                        getAttributes(ReturnIndex)))) :
788     AttributeSet();
789 }
790
791 AttributeSet AttributeSet::getFnAttributes() const {
792   return pImpl && hasAttributes(FunctionIndex) ?
793     AttributeSet::get(pImpl->getContext(),
794                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
795                         std::make_pair(FunctionIndex,
796                                        getAttributes(FunctionIndex)))) :
797     AttributeSet();
798 }
799
800 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
801   AttributeSetNode *ASN = getAttributes(Index);
802   return ASN ? ASN->hasAttribute(Kind) : false;
803 }
804
805 bool AttributeSet::hasAttribute(unsigned Index, StringRef Kind) const {
806   AttributeSetNode *ASN = getAttributes(Index);
807   return ASN ? ASN->hasAttribute(Kind) : false;
808 }
809
810 bool AttributeSet::hasAttributes(unsigned Index) const {
811   AttributeSetNode *ASN = getAttributes(Index);
812   return ASN ? ASN->hasAttributes() : false;
813 }
814
815 /// \brief Return true if the specified attribute is set for at least one
816 /// parameter or for the return value.
817 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
818   if (pImpl == 0) return false;
819
820   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
821     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
822            IE = pImpl->end(I); II != IE; ++II)
823       if (II->hasAttribute(Attr))
824         return true;
825
826   return false;
827 }
828
829 Attribute AttributeSet::getAttribute(unsigned Index,
830                                      Attribute::AttrKind Kind) const {
831   AttributeSetNode *ASN = getAttributes(Index);
832   return ASN ? ASN->getAttribute(Kind) : Attribute();
833 }
834
835 Attribute AttributeSet::getAttribute(unsigned Index,
836                                      StringRef Kind) const {
837   AttributeSetNode *ASN = getAttributes(Index);
838   return ASN ? ASN->getAttribute(Kind) : Attribute();
839 }
840
841 unsigned AttributeSet::getParamAlignment(unsigned Index) const {
842   AttributeSetNode *ASN = getAttributes(Index);
843   return ASN ? ASN->getAlignment() : 0;
844 }
845
846 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
847   AttributeSetNode *ASN = getAttributes(Index);
848   return ASN ? ASN->getStackAlignment() : 0;
849 }
850
851 std::string AttributeSet::getAsString(unsigned Index,
852                                       bool InAttrGrp) const {
853   AttributeSetNode *ASN = getAttributes(Index);
854   return ASN ? ASN->getAsString(InAttrGrp) : std::string("");
855 }
856
857 /// \brief The attributes for the specified index are returned.
858 AttributeSetNode *AttributeSet::getAttributes(unsigned Index) const {
859   if (!pImpl) return 0;
860
861   // Loop through to find the attribute node we want.
862   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
863     if (pImpl->getSlotIndex(I) == Index)
864       return pImpl->getSlotNode(I);
865
866   return 0;
867 }
868
869 AttributeSet::iterator AttributeSet::begin(unsigned Slot) const {
870   if (!pImpl)
871     return ArrayRef<Attribute>().begin();
872   return pImpl->begin(Slot);
873 }
874
875 AttributeSet::iterator AttributeSet::end(unsigned Slot) const {
876   if (!pImpl)
877     return ArrayRef<Attribute>().end();
878   return pImpl->end(Slot);
879 }
880
881 //===----------------------------------------------------------------------===//
882 // AttributeSet Introspection Methods
883 //===----------------------------------------------------------------------===//
884
885 /// \brief Return the number of slots used in this attribute list.  This is the
886 /// number of arguments that have an attribute set on them (including the
887 /// function itself).
888 unsigned AttributeSet::getNumSlots() const {
889   return pImpl ? pImpl->getNumAttributes() : 0;
890 }
891
892 unsigned AttributeSet::getSlotIndex(unsigned Slot) const {
893   assert(pImpl && Slot < pImpl->getNumAttributes() &&
894          "Slot # out of range!");
895   return pImpl->getSlotIndex(Slot);
896 }
897
898 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
899   assert(pImpl && Slot < pImpl->getNumAttributes() &&
900          "Slot # out of range!");
901   return pImpl->getSlotAttributes(Slot);
902 }
903
904 uint64_t AttributeSet::Raw(unsigned Index) const {
905   // FIXME: Remove this.
906   return pImpl ? pImpl->Raw(Index) : 0;
907 }
908
909 void AttributeSet::dump() const {
910   dbgs() << "PAL[\n";
911
912   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
913     uint64_t Index = getSlotIndex(i);
914     dbgs() << "  { ";
915     if (Index == ~0U)
916       dbgs() << "~0U";
917     else
918       dbgs() << Index;
919     dbgs() << " => " << getAsString(Index) << " }\n";
920   }
921
922   dbgs() << "]\n";
923 }
924
925 //===----------------------------------------------------------------------===//
926 // AttrBuilder Method Implementations
927 //===----------------------------------------------------------------------===//
928
929 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
930   : Attrs(0), Alignment(0), StackAlignment(0) {
931   AttributeSetImpl *pImpl = AS.pImpl;
932   if (!pImpl) return;
933
934   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
935     if (pImpl->getSlotIndex(I) != Index) continue;
936
937     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
938            IE = pImpl->end(I); II != IE; ++II)
939       addAttribute(*II);
940
941     break;
942   }
943 }
944
945 void AttrBuilder::clear() {
946   Attrs.reset();
947   Alignment = StackAlignment = 0;
948 }
949
950 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
951   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
952   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
953          "Adding alignment attribute without adding alignment value!");
954   Attrs[Val] = true;
955   return *this;
956 }
957
958 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
959   if (Attr.isStringAttribute()) {
960     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
961     return *this;
962   }
963
964   Attribute::AttrKind Kind = Attr.getKindAsEnum();
965   Attrs[Kind] = true;
966
967   if (Kind == Attribute::Alignment)
968     Alignment = Attr.getAlignment();
969   else if (Kind == Attribute::StackAlignment)
970     StackAlignment = Attr.getStackAlignment();
971   return *this;
972 }
973
974 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
975   TargetDepAttrs[A] = V;
976   return *this;
977 }
978
979 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
980   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
981   Attrs[Val] = false;
982
983   if (Val == Attribute::Alignment)
984     Alignment = 0;
985   else if (Val == Attribute::StackAlignment)
986     StackAlignment = 0;
987
988   return *this;
989 }
990
991 AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
992   unsigned Slot = ~0U;
993   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
994     if (A.getSlotIndex(I) == Index) {
995       Slot = I;
996       break;
997     }
998
999   assert(Slot != ~0U && "Couldn't find index in AttributeSet!");
1000
1001   for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot); I != E; ++I) {
1002     Attribute Attr = *I;
1003     if (Attr.isEnumAttribute() || Attr.isAlignAttribute()) {
1004       Attribute::AttrKind Kind = I->getKindAsEnum();
1005       Attrs[Kind] = false;
1006
1007       if (Kind == Attribute::Alignment)
1008         Alignment = 0;
1009       else if (Kind == Attribute::StackAlignment)
1010         StackAlignment = 0;
1011     } else {
1012       assert(Attr.isStringAttribute() && "Invalid attribute type!");
1013       std::map<std::string, std::string>::iterator
1014         Iter = TargetDepAttrs.find(Attr.getKindAsString());
1015       if (Iter != TargetDepAttrs.end())
1016         TargetDepAttrs.erase(Iter);
1017     }
1018   }
1019
1020   return *this;
1021 }
1022
1023 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1024   std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
1025   if (I != TargetDepAttrs.end())
1026     TargetDepAttrs.erase(I);
1027   return *this;
1028 }
1029
1030 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
1031   if (Align == 0) return *this;
1032
1033   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1034   assert(Align <= 0x40000000 && "Alignment too large.");
1035
1036   Attrs[Attribute::Alignment] = true;
1037   Alignment = Align;
1038   return *this;
1039 }
1040
1041 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
1042   // Default alignment, allow the target to define how to align it.
1043   if (Align == 0) return *this;
1044
1045   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1046   assert(Align <= 0x100 && "Alignment too large.");
1047
1048   Attrs[Attribute::StackAlignment] = true;
1049   StackAlignment = Align;
1050   return *this;
1051 }
1052
1053 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1054   // FIXME: What if both have alignments, but they don't match?!
1055   if (!Alignment)
1056     Alignment = B.Alignment;
1057
1058   if (!StackAlignment)
1059     StackAlignment = B.StackAlignment;
1060
1061   Attrs |= B.Attrs;
1062
1063   for (td_const_iterator I = B.TargetDepAttrs.begin(),
1064          E = B.TargetDepAttrs.end(); I != E; ++I)
1065     TargetDepAttrs[I->first] = I->second;
1066
1067   return *this;
1068 }
1069
1070 bool AttrBuilder::contains(StringRef A) const {
1071   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1072 }
1073
1074 bool AttrBuilder::hasAttributes() const {
1075   return !Attrs.none() || !TargetDepAttrs.empty();
1076 }
1077
1078 bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
1079   unsigned Slot = ~0U;
1080   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1081     if (A.getSlotIndex(I) == Index) {
1082       Slot = I;
1083       break;
1084     }
1085
1086   assert(Slot != ~0U && "Couldn't find the index!");
1087
1088   for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot);
1089        I != E; ++I) {
1090     Attribute Attr = *I;
1091     if (Attr.isEnumAttribute() || Attr.isAlignAttribute()) {
1092       if (Attrs[I->getKindAsEnum()])
1093         return true;
1094     } else {
1095       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1096       return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
1097     }
1098   }
1099
1100   return false;
1101 }
1102
1103 bool AttrBuilder::hasAlignmentAttr() const {
1104   return Alignment != 0;
1105 }
1106
1107 bool AttrBuilder::operator==(const AttrBuilder &B) {
1108   if (Attrs != B.Attrs)
1109     return false;
1110
1111   for (td_const_iterator I = TargetDepAttrs.begin(),
1112          E = TargetDepAttrs.end(); I != E; ++I)
1113     if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1114       return false;
1115
1116   return Alignment == B.Alignment && StackAlignment == B.StackAlignment;
1117 }
1118
1119 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
1120   // FIXME: Remove this in 4.0.
1121   if (!Val) return *this;
1122
1123   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1124        I = Attribute::AttrKind(I + 1)) {
1125     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
1126       Attrs[I] = true;
1127  
1128       if (I == Attribute::Alignment)
1129         Alignment = 1ULL << ((A >> 16) - 1);
1130       else if (I == Attribute::StackAlignment)
1131         StackAlignment = 1ULL << ((A >> 26)-1);
1132     }
1133   }
1134  
1135   return *this;
1136 }
1137
1138 //===----------------------------------------------------------------------===//
1139 // AttributeFuncs Function Defintions
1140 //===----------------------------------------------------------------------===//
1141
1142 /// \brief Which attributes cannot be applied to a type.
1143 AttributeSet AttributeFuncs::typeIncompatible(Type *Ty, uint64_t Index) {
1144   AttrBuilder Incompatible;
1145
1146   if (!Ty->isIntegerTy())
1147     // Attribute that only apply to integers.
1148     Incompatible.addAttribute(Attribute::SExt)
1149       .addAttribute(Attribute::ZExt);
1150
1151   if (!Ty->isPointerTy())
1152     // Attribute that only apply to pointers.
1153     Incompatible.addAttribute(Attribute::ByVal)
1154       .addAttribute(Attribute::Nest)
1155       .addAttribute(Attribute::NoAlias)
1156       .addAttribute(Attribute::NoCapture)
1157       .addAttribute(Attribute::StructRet);
1158
1159   return AttributeSet::get(Ty->getContext(), Index, Incompatible);
1160 }